removeObjectAtIndex导致“消息发送到解除分配的实例”

时间:2011-10-27 06:52:39

标签: objective-c ios nsmutablearray automatic-ref-counting

我正在将一些代码转换为ARC。代码在NSMutableArray中搜索元素,然后查找,删除并返回该元素。问题是该元素在“removeObjectAtIndex”后立即被释放:

- (UIView *)viewWithTag:(int)tag
{
    UIView *view = nil;
    for (int i = 0; i < [self count]; i++)
    {
        UIView *aView = [self objectAtIndex:i];
        if (aView.tag == tag) 
        {
            view = aView;
            NSLog(@"%@",view); // 1 (view is good)
            [self removeObjectAtIndex:i];
            break;
        }
    }
    NSLog(@"%@",view); // 2 (view has been deallocated)
    return view;
}

当我运行它时,我得到了

*** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0

在第二个日志声明中。

预ARC,在调用removeObjectAtIndex:之前我小心保留了对象,然后自动释放它。我如何告诉ARC做同样的事情?

1 个答案:

答案 0 :(得分:5)

使用UIView *view限定符声明__autoreleasing引用,如下所示:

- (UIView *)viewWithTag:(int)tag
{
    __autoreleasing UIView *view;
    __unsafe_unretained UIView *aView;

    for (int i = 0; i < [self count]; i++)
    {
        aView = [self objectAtIndex:i];
        if (aView.tag == tag) 
        {
            view = aView;
            //Since you declared "view" as __autoreleasing,
            //the pre-ARC equivalent would be:
            //view = [[aView retain] autorelease];

            [self removeObjectAtIndex:i];
            break;
        }
    }

    return view;
}

__autoreleasing会为您提供 完全 您想要的内容,因为在分配时,新的指针会被保留,自动释放,然后存储到左值。

请参阅ARC reference