小编lew*_*son的帖子

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

我正在将一些代码转换为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;
}
Run Code Online (Sandbox Code Playgroud)

当我跑它,我得到

*** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0
Run Code Online (Sandbox Code Playgroud)

在第二个日志声明中.

在ARC之前,我小心地在调用removeObjectAtIndex:之前保留对象,然后自动释放它.我怎么告诉ARC做同样的事情?

objective-c nsmutablearray ios automatic-ref-counting

6
推荐指数
1
解决办法
940
查看次数