1

I'm working with some Objective-C code, and I was wondering..I noticed, while learning about NSNotificationCenter, that it's generally good practice to remove an NSNotificationCenter observers on dealloc. However, in the case of using an auto release pool - is this taken care of, or do I still need a dealloc method for it?

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:XBPageCurlViewDidSnapToPointNotification object:nil];
}

Thanks in advance!

mattsven
  • 22,305
  • 11
  • 68
  • 104

3 Answers3

3

You will need to take care of removing observers added within the lifetime of that class instance, no matter what.

If that notification in question does get triggered, it will try to invoke your instance. If that instance has become invalid (e.g. due to deallocation), your app will crash.

As a rule of thumb, UIKit does not by itself use ARC (generally with exceptions) and hence will not adhere to weak references.

Till
  • 27,559
  • 13
  • 88
  • 122
1

I don't believe that NSNotificationCenter supports weak referencing. It instead uses unsafe_unretained references, so you will probably end up with a dangling pointer if you do not clean it up in dealloc.

borrrden
  • 33,256
  • 8
  • 74
  • 109
1

You still need to take care of removing observer in every case.
Your autorelease pool just holds your objects till pool is not released once pool is released it sends release message to each object and if that object's retain count becomes zero it is deallocated. Before deallocating it's dealloc method is called.
P.S. Auto release pool doesn't care what's going inside your dealloc method.

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184