Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did my app crash when assigning self to __weak local under ARC?

Crashlytics reported this crash:

0    libobjc.A.dylib     _objc_trap() + 18446744073709552000
1    libobjc.A.dylib     _objc_fatal + 71
2    libobjc.A.dylib     append_referrer_no_lock(weak_referrer_array_t*, objc_object**)
3    libobjc.A.dylib     objc_storeWeak + 120
4    MyApp               CloudSyncButton.m line 58 -[CloudSyncButton observeValueForKeyPath:ofObject:change:context:]
5    ....

The code in question:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    CloudSyncButton* __weak weakSelf = self;  //<---crashed here
    if([keyPath isEqualToString:kCloudSyncingKVO]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CloudSyncButton* localSelf = weakSelf;
            [localSelf refreshCloudSyncIcon];
        });
    }
}

I need help understanding why this crashed and what I can do to avoid it in the future. This is the first time I've seen something like this crash, so I'm wondering if it is a fluke?

like image 538
Tim Reddy Avatar asked Jun 03 '13 14:06

Tim Reddy


1 Answers

Make sure that in all cases your CloudSyncButton has removed itself from observing other objects in its dealloc method. It would appear this message is getting sent after your button has been deallocated.

like image 147
David H Avatar answered Mar 20 '23 16:03

David H