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

}

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.


- (void) dealloc will not be called in ARC environment. Instread, you can remove your observer before add 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];     
  }
}
链接地址: http://www.djcxy.com/p/25748.html

上一篇: WordPress的邮件头设置其他纯文本

下一篇: NSNotificationCenter多次拨打电话