gpt4 book ai didi

objective-c - removeObjectAtIndex 导致 "message sent to deallocated instance"

转载 作者:可可西里 更新时间:2023-11-01 03:55:27 26 4
gpt4 key购买 nike

我正在将一些代码转换为 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 做同样的事情?

最佳答案

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

- (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

关于objective-c - removeObjectAtIndex 导致 "message sent to deallocated instance",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7912550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com