使用相同的对象NSNotificationCenter释放两次调用

时间:2014-02-14 11:32:34

标签: ios objective-c memory-management nsnotificationcenter nszombie

我想在视图A中传递一个对象来查看B,这是有效的,但是当我重复这个方法时,我遇到了崩溃(线程1:EXC_BREAKPOINT)。

我在我的视图B中初始化为:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hotSpotMore:) name:@"HotSpotTouched" object:nil];
    }
    return self;
}


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

        self.articleVC = [[ArticlesVC alloc] init];
        self.articleVC=[notification.userInfo objectForKey:@"Art"]; // ERROR LINE


    }

在我的视图A中:

        NSDictionary *myDictionary=[NSDictionary dictionaryWithObject:articles forKey:@"Art"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"HotSpotTouched" object:self userInfo:myDictionary];

我在实例变量中恢复了我的对象,前两次,这是有效的,并且在发生崩溃之后。

输出: ArticlesVC setArticleVC:]:发送到解除分配的实例0x44883f10的消息

在我的乐器Zombie中我有这样的错误: Objective-C消息被发送到解除分配的'ArticlesVC'对象(僵尸),地址为:0xc2d0710。 

我的问题是方法dealloc被调用两次我有一个Zombie因为我的“RefCt”设置为“-1”,我不明白为什么这个方法被调用两次。我怎么解决这个问题?

2 个答案:

答案 0 :(得分:1)

您的viewB已被解除分配,但viewA会将对象发送至已存在的viewB。将removeObserver添加到dealloc

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

答案 1 :(得分:0)

每次为类调用initWithNibName时,都会添加通知观察器。 尝试删除之前的观察者,然后再添加新观察者。

您可以在

中执行此操作
- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewdidUnload 
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}