简体   繁体   中英

BAD_ACCESS when calling Notification

I have class A and class BI am calling class B from class A.Here my problem is width and height of class A is depending on class B.when sizeForScrollView property (class B property) changed i want notification.everything is working fine.But when i am reloading class A at that time it is crashing from class B notification line.

Here is code :

class 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);

}

class 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];

Please help me.Thanking you.

Make sure instances of class A are removing themselves as observers on dealloc. Otherwise if you release an instance, the notification center will still try to talk to it after it's been released, causing an EXC_BAD_ACCESS crash.

If you're not using ARC, that would look something like this (in class A):

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

This is necessary because adding an object as an observer does not increment its retain count. The notification center doesn't take ownership of the observer or do anything to track whether it's still around or not.

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

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM