【发布时间】:2014-02-27 05:21:05
【问题描述】:
有人可以解释为什么我的代码崩溃了吗?崩溃发生在 foo 方法的块内。 我有 EXC_BAD_ACCESS 或“对象错误:双重释放”。当我将“启用僵尸对象”设置为 ON 时,我还收到了“-[NSObject description]: message sent to deallocated instance”。
@interface ViewController ()
@property (nonatomic, strong) NSObject *obj;
@end
@implementation ViewController
// just adding button
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:@"test" forState:UIControlStateNormal];
btn.frame = CGRectMake(100, 100, 100, 100);
[btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
// fired by button
- (void)btnAction:(id)sender {
for (int i = 0; i < 100; i++) {
[self foo];
}
}
// I want to understand this method
- (void)foo {
NSLog(@"foo");
self.obj = NSObject.new;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"%@", [[self obj] description]); // sometimes crash happenes here with a message "-[NSObject description]: message sent to deallocated instance"
});
}
@end
看起来 self.obj 在 [self obj] 和 [obj description] 之间被释放。但我不确定为什么。
我认为来自 [self obj] 的对象应该归其作用域所有,即使 self.obj = NSObject.new 在其他线程上同时执行也不应该被释放。 是不是我的理解错了?
我正在使用 ARC 在 iOS 7.0.4 上进行测试。谢谢!
【问题讨论】:
-
这是你的真实代码吗?
[self obj] description]看起来不会编译。 -
你为什么要在后台登录?
-
@AaronBrager 很抱歉这是我的错误。更新帖子!
-
@rmaddy 没有任何意义。我的真实代码更复杂。我只是尝试制作最简单的示例代码来解决这个问题。
标签: ios objective-c memory-management automatic-ref-counting