在将以下代码更新为iOS 5的自动引用计数时,当尝试执行快速枚举以便使用“foreach”循环遍历实现类时,发生了一个错误,即在将缓冲区分配给“state->itemPtr”时发生错误。我遇到的错误是“将'__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;
}
在这个例子中,_tuples变量是类型为NSMutableArray的实例变量。
我该如何解决这个错误?
state->mutationsPtr
不应该用于存储self
,它应该指向额外的字段(简单方式)以便不使用,或者指向您的类中某种在集合更改时发生变化的内部值(困难方式)。我将编辑答案以包括简单的方法。 - Daniel- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len;
。 - Steven Fisher