1

我有 A 类和 BI 类从 A 类调用 B 类。这里我的问题是 A 类的宽度和高度取决于 B 类。当sizeForScrollView属性(B 类属性)改变时我想要通知。一切正常。但是当我当时正在重新加载 A 类,它正在从 B 类通知行崩溃。

这是代码:

A级

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (changeContentSize) name:@"MyNotification" object:nil];
-(void)changeContentSize{
    self.scrollView.contentSize = CGSizeMake(self.aSubjectView.sizeForScrollView.width, self.aSubjectView.sizeForScrollView.height);
    self.aSubjectView.frame = CGRectMake(frameForView.origin.x, frameForView.origin.y, frameForView.size.width, self.aSubjectView.sizeForScrollView.height);

}

B类

CGRect rect;
rect.size.width = self.frame.size.width;
rect.size.height = heightForSubject + 10;
rect.origin = self.frame.origin;
sizeForScrollView = rect.size;
NSNotification* notification = [NSNotification notificationWithName:@"MyNotification" object:self];
        [[NSNotificationCenter defaultCenter] postNotification:notification];

请帮助我。谢谢。

4

2 回答 2

2

确保类 A 的实例将自己作为 dealloc 上的观察者移除。否则,如果你释放了一个实例,通知中心在它被释放后仍然会尝试与它对话,从而导致 EXC_BAD_ACCESS 崩溃。

如果你不使用 ARC,那看起来像这样(在 A 类中):

- (void)dealloc 
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc]; // Take this line out if you are using ARC
}

这是必要的,因为将对象添加为观察者不会增加其保留计数。通知中心不获取观察者的所有权,也不做任何事情来跟踪它是否仍然存在。

于 2013-08-30T07:34:14.187 回答
0

在 viewDidUnload 中删除“MyNotification”的观察者

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
于 2013-08-30T09:11:03.993 回答