lew*_*son 6 objective-c nsmutablearray ios 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;
}
Run Code Online (Sandbox Code Playgroud)
当我跑它,我得到
*** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0
Run Code Online (Sandbox Code Playgroud)
在第二个日志声明中.
在ARC之前,我小心地在调用removeObjectAtIndex:之前保留对象,然后自动释放它.我怎么告诉ARC做同样的事情?
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;
}
Run Code Online (Sandbox Code Playgroud)
__autoreleasing会给你究竟想要什么,因为在分配新指针对象被保留,自动释放,然后存储到左值.
请参阅ARC参考