NSNotificationCenter多次呼叫

时间:2015-04-20 09:23:26

标签: ios objective-c iphone nsnotificationcenter nsnotification

我已在我的应用程序中实现了NSNotificationCenter。我在完成图像解码时发送通知。第一次图像解码将完成8次。所以通知假设发送8次。但是它正在调用64次(8 * 8)。

这是我的代码我是如何实现的 - >                 //初始化

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

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

//调用方法

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

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

//取消分配

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

//发布通知

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

有人可以建议我做错了。

提前致谢。

//调用方法是这样的(调用8次)

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

}

2 个答案:

答案 0 :(得分:5)

<强>解决方案: 我重新检查了我的代码, initWithFrame:(CGRect)框架正在调用8次并添加NSNotification观察者8次。

所以我改变了这样的代码,---&gt;&gt;初始化。

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

---&GT;&GT;解除分配

- (void) dealloc
  {
    note=true;

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

现在 addObserver 方法只调用一次,所以问题解决了。 谢谢大家的宝贵指导。

答案 1 :(得分:-2)

在ARC环境中不会调用

- (void) dealloc。 Instread,您可以在添加之前删除您的观察者:

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