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;
}
当我运行它时,我得到
*** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0
第二条日志语句。
在 ARC 之前,我在调用 removeObjectAtIndex: 之前小心地保留对象,然后自动释放它。我如何告诉 ARC 做同样的事情?
I am converting some code to ARC. The code searches for an element in an NSMutableArray, then finds, removes, and returns that element. The problem is that the element gets deallocated immediately upon "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;
}
When I run it, I get
*** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0
at the second log statement.
Pre-ARC, I was careful to retain the object before calling removeObjectAtIndex:, and then to autorelease it. How do I tell ARC to do the same thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
__autoreleasing
限定符声明UIView *view
引用,如下所示:__autoreleasing
将为您提供准确 你想要什么,因为在分配时,新的指针被保留,自动释放,然后存储到左值中。请参阅 ARC 参考
Declare the
UIView *view
reference with the__autoreleasing
qualifier, like so:__autoreleasing
will give you exactly what you want because on assignment the new pointee is retained, autoreleased, and then stored into the lvalue.See the ARC reference