NSFastEnumeration协议和ARC的问题

时间:2013-01-24 13:12:53

标签: 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);
}

1 个答案:

答案 0 :(得分:5)

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

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

ZBarSymbol * __autoreleasing tmp = [[ZBarSymbol alloc] initWithSymbol: sym];
*stackbuf = tmp;