NSFastEnumeration协议和ARC的问题

Tom*_*Tom 3 xcode automatic-ref-counting

在将Objective-C代码迁移到ARC时,我无法实现NSFastEnumeration协议.有人能告诉我,如何摆脱以下warnig(参见代码片段)?提前致谢.

// I changed it due to ARC, was before
// - (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*) state objects: (id*) stackbuf count: (NSUInteger) len
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*) state objects: (__unsafe_unretained id *) stackbuf count: (NSUInteger) len
{
    ... 
    *stackbuf = [[ZBarSymbol alloc] initWithSymbol: sym]; //Warning: Assigning retained object to unsafe_unretained variable; object will be released after assignment
    ... 
}

- (id) initWithSymbol: (const zbar_symbol_t*) sym
{
    if(self = [super init]) {
        ... 
    }
    return(self);
}
Run Code Online (Sandbox Code Playgroud)

jat*_*ben 5

对于ARC,某些东西必须对每个对象保持强烈或自动释放的引用,否则它将被释放(正如警告所说).由于stackbuf__unsafe_unretained,它不会挂到ZBarSymbol你.

如果您创建一个临时自动释放变量并将对象存储在那里,它将一直存在,直到弹出当前的自动释放池.然后你可以stackbuf毫无怨言地指出它.

ZBarSymbol * __autoreleasing tmp = [[ZBarSymbol alloc] initWithSymbol: sym];
*stackbuf = tmp;
Run Code Online (Sandbox Code Playgroud)