我正在将一些代码转换为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做同样的事情?
答案 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
会为您提供 完全 您想要的内容,因为在分配时,新的指针会被保留,自动释放,然后存储到左值。