自动引用计数:快速枚举时出错

在更新下面的代码以使用iOS 5自动引用计数时,当尝试执行快速枚举时将“state-> itemPtr”分配给缓冲区时会发生错误,以便可以使用“foreach”循环迭代实现类。 我得到的错误是“指定'__autoreleasing id *'为'__unsafe_unretained id *'更改指针保留/释放属性”。 查看带注释的代码行。

/* * @see http://cocoawithlove.com/2008/05/implementing-countbyenumeratingwithstat.html * @see http://www.mikeash.com/pyblog/friday-qa-2010-04-16-implementing-fast-enumeration.html */ - (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState *)state objects: (id *)buffer count: (NSUInteger)bufferSize { NSUInteger arrayIndex = (NSUInteger)state->state; NSUInteger arraySize = [_tuples count]; NSUInteger bufferIndex = 0; while ((arrayIndex < arraySize) && (bufferIndex < bufferSize)) { buffer[bufferIndex] = [_tuples objectAtIndex: arrayIndex]; arrayIndex++; bufferIndex++; } state->state = (unsigned long)arrayIndex; state->itemsPtr = buffer; // Assigning '__autoreleasing id *' to '__unsafe_unretained id*' changes retain/release properties of pointer state->mutationsPtr = (unsigned long *)self; return bufferIndex; } 

本例中的_tuplesvariables是一个NSMutableArraytypes的实例variables。

我该如何解决这个错误?

您需要将缓冲区更改为__unsafe_unretained

 - (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState *)state objects: (id __unsafe_unretained *)buffer count: (NSUInteger)bufferSize 

资源

编辑:简单的方法来摆脱mutationPtr中的错误:

 state->mutationsPtr = &state->extra[0]; 

Ziminji,

我遇到了同样的问题,这就是我遇到这个问题的原因。

我通过保持 objects参数的定义(如保持为id * )来解决这个问题,而是使用void指针来进行双重转换。

所以,虽然这给我产生了错误:

 state->itemsPtr = (__unsafe_unretained id *)buffer // Error 

这工作很好:

 state->itemsPtr = (__unsafe_unretained id *)(void *)buffer // No error 

免责声明:我不是ARC专家,我不能保证,这不会引起问题引用计数。 但是,它似乎在我的testing中正常工作,它肯定编译没有警告。

顺便说一下,我遇到了这个两部分的博客文章,其中涵盖了很多深度的快速枚举:

  • 快速枚举,第1部分
  • 快速枚举,第2部分

还有__unsafe_unretained这个博客条目:

  • 不安全在任何速度