objective c - How does the NSNotificationCenter detect the deallocated observer in ARC? -


i found when using nsnotificationcenter in arc, forget remove observer defaultcenter, , observer has deallocated, post notification observer observed , there no crash anymore !!

before xcode 4, there no arc, must remove observer default notification center in dealloc function, this:

- (void)dealloc {     [[nsnotificationcenter defaultcenter] removeobserver:self]; } 

otherwise when binded notification posted, triger crash !

so, question how nsnotificationcenter detect deallocated observer in arc ?

update: of ios 9 , os x 10.11, no longer necessary nsnotificationcenter observer un-register when being deallocated. (source: unregistering nsnotificationcenter observers in ios 9)


(old answer:) arc, have remove observer notification center when deallocated. may pure chance program did not crash.

the following program demonstrates this. have activated "enable zombie objects" option.

@interface myobject : nsobject @end  @implementation  myobject  -(id)init {     self = [super init];     if (self) {         [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(notify:) name:@"test" object:nil];     }     return self; } - (void)dealloc {     nslog(@"dealloc");     //[[nsnotificationcenter defaultcenter] removeobserver:self]; } - (void)notify:(nsnotification *)notification {     nslog(@"notify"); }  @end  int main(int argc, const char * argv[]) {     @autoreleasepool {         myobject *o = [[myobject alloc] init];         [[nsnotificationcenter defaultcenter] postnotificationname:@"test" object:nil];         o = nil; // causes object deallocated         // ... , crash         [[nsnotificationcenter defaultcenter] postnotificationname:@"test" object:nil];     }     return 0; } 

output:

notifytest[593:303] notify notifytest[593:303] dealloc notifytest[593:303] *** -[myobject notify:]: message sent deallocated instance 0x100114290 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -