ios - 调用通知时 BAD_ACCESS

标签 ios objective-c notifications exc-bad-access

我有 A 类和 B 类。我正在从 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];

请帮助我。谢谢。

最佳答案

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

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

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

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

关于ios - 调用通知时 BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18524962/

相关文章:

android - AlarmManager 的更新时间 (Android)

ios - Apple 会批准那里的 UIButtons 吗?

ios - 多个自定义 UITableViewCell

java - 将 iPhone 应用程序转换为 Android 应用程序——我需要了解 Objective C 吗?

iphone - SIGABRT 错误 - NSUnknownKeyExeption (SetValue :forUndefinedKey;)

android - 无法在 Android < 5.0 上删除通知

android - 无法检索新的 intent extra

ios - 在两个 UIViewController 堆栈之间转换

ios - 添加约束后仍然存在不明确的可滚动内容高度错误

objective-c - 当我尝试在 iOS 应用程序的 NSURL 中传递参数时,为什么会出现此错误?