NSNotificationCenter calls several times

I implemented NSNotificationCenter in my application. I send a notification when image decoding is performed. The first time decoding an image will be performed 8 times. So the notification should be sent 8 times. But it calls 64 times (8 * 8).

Here is my code as I implemented → // Initialization

- (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getHRImage:) name:@"DecodeComplete" object:nil];} 

// call method

  -(void)getHRImage:(NSNotification *) notification { if ([[notification name] isEqualToString:@"DecodeComplete"]) NSLog (@"Successfully received the DecodeComplete notification! "); }` 

// release

 - (void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:self]; //[super dealloc]; } 

// Email Notification

 [[NSNotificationCenter defaultCenter] postNotificationName:@"DecodeComplete" object:self]; 

Someone can tell me where I was wrong.

Thanks in advance.

// The call method is similar (call 8 times)

 -(void)decode { NSLog(@"---------- Decoding is Complete ---------"); [[NSNotificationCenter defaultCenter] postNotificationName:@"MdjDecodeComplete" object:self]; } 
+7
ios objective-c iphone nsnotificationcenter nsnotification
source share
2 answers

Solution: I double-checked my code, the initWithFrame: frame (CGRect) calls 8 times and adds an NSNotification observer 8 times.

So, I changed my code as follows: --- → Initialization.

 static bool note=YES; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { if(note) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getHRImage:) name:@"DecodeComplete" object:nil]; note=NO;} 

--- → Release

 - (void) dealloc { note=true; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:nil]; //[super dealloc]; } 

Now the addObserver method calls only once, so my problem is resolved. Thanks to everyone for the valuable guidance.

+5
source share

- (void) dealloc will not be called in the ARC environment. Instread, you can remove your observer before adding it like this:

 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:self]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getHRImage:) name:@"DecodeComplete" object:nil]; } } 
-2
source share

All Articles