【问题标题】:NSArray enumerateUsingBlock: can I access object at other index inside block?NSArray enumerateUsingBlock:我可以访问块内其他索引处的对象吗?
【发布时间】:2012-08-15 16:37:59
【问题描述】:

我可以这样做吗?

[array enumerateUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
    if (idx > 1)
    {
        NSUInteger previous1 = [array objectAtIndex: idx - 1].value;
        NSUInteger previous2 = [array objectAtIndex: idx - 2].value;
        obj.value = previous1 + previous2;
    }
}];

这样做安全吗?我不是在枚举块内的数组(或可变数组)中添加/删除对象,我只是在其他 idx 中获取/更改对象的值。

谢谢

【问题讨论】:

    标签: objective-c nsmutablearray nsarray objective-c-blocks enumeration


    【解决方案1】:

    没关系,只是你必须先将对象转换为正确的类型,然后才能使用点语法获取 value 属性。

    【讨论】:

    • 如果使用数组中对象的实际类型声明块,则可以避免强制转换:^(MyType *obj, NSUInteger idx, BOOL *stop)
    • 那么[array objectAtIndex:]的结果还是需要的
    猜你喜欢
    • 2016-11-07
    • 2020-11-20
    • 1970-01-01
    • 2019-02-11
    • 2011-04-28
    • 2018-09-27
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    相关资源
    最近更新 更多