NSNotificationCenter多次拨打电话
我在我的应用程序中实施了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];
}
解决方案:我重新检查了我的代码, initWithFrame:(CGRect)框架正在调用8次,并添加了8次NSNotification观察器。
所以我改变了我的代码 - >> 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;}   
--- >>重新分配
- (void) dealloc
  {
    note=true;
  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DecodeComplete" object:nil];
//[super dealloc];
}
现在addObserver方法只调用一次,所以我的问题得到解决。 谢谢大家的宝贵指导。
  - (void) dealloc不会在ARC环境中调用。  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];     
  }
}
                        链接地址: http://www.djcxy.com/p/25747.html
                        上一篇: NSNotificationCenter is calling multiple times
下一篇: mouseleave not firing after mouseenter changes HTML within anchor
