0

We have on class that is observe the notification with -[NSNotificationCenter addObserverForName:object:queue:usingBlock:] but it is randomly crash with EXC_BAD_ACCESS.

@interface Test: NSObject {
  id obs; 
}

@end


@implementation Test
- (id)init {

  self = [super init];

  if (self) {

    Test * __weak weakSelf = self;

    self->obs = [[NSNotificationCenter defaultCenter] addObserverForName:Notification object:nil queue:nil usingBlock:^(NSNotification *note) {

           Test *strongSelf = weakSelf;

           if (!strongSelf) {

            return;

          }



      [strongSelf handleNotification:note];

    }];
  }

  return self;
}

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

      self->obs = nil;
}    

@end

We found that sometimes when the notification is posted NSNotificationCenter has already get the observer and prepare to call the block for the notification but in the mean time, this object is dealloced and so with the self->obs, which make it crash on [NSNotification postNotification...] method because of the zombie self->obs

Are there any workaround or fix on this issue?

PS. This is ARC code.

1 Answers1

0

Are there any workaround for randomly crash?

Enable zombies - this will cause the exception to breakpoint on the offending line. From there it will be a lot easier to figure out than the general EXC_BAD_ACCESS crash.

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174