Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter is calling multiple times

I have implemented NSNotificationCenter in my application. I send notification when ever image decoding is done. first time the image decoding will be done 8 times.So the notification suppose to send 8 times.But it is calling 64 times(8*8).

Here is my code how i have implemented--> // Initialisation

- (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
 if (self) {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                      selector:@selector(getHRImage:)
                                                             name:@"DecodeComplete" object:nil];}   

//Calling Method

 -(void)getHRImage:(NSNotification *) notification
{

if ([[notification name] isEqualToString:@"DecodeComplete"])
    NSLog (@"Successfully received the DecodeComplete notification! ");
}`

// Deallocation

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

//Post Notification

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

Some one can suggest me where I have done wrong.

Thanks in advance.

//Calling Method is like this (calling 8 times)

-(void)decode
{
   NSLog(@"---------- Decoding is Complete ---------");
     [[NSNotificationCenter defaultCenter]  postNotificationName:@"MdjDecodeComplete" object:self];

}
like image 514
Kiran Kumar Avatar asked Apr 20 '15 09:04

Kiran Kumar


1 Answers

Solution: I rechecked my code, the initWithFrame:(CGRect)frame is calling 8 times and adding NSNotification observer 8 times.

So i have changed my code like this, --->> Initialisation.

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;}   

--->> Deallocation

- (void) dealloc
  {
    note=true;

  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:nil];
//[super dealloc];
}

Now addObserver method is calling only one time so my problem is resolved. Thank you all for your valuable guidance.

like image 102
Kiran Kumar Avatar answered Oct 14 '22 07:10

Kiran Kumar