Here are the three magic words: +alloc, -copy and +new. If you commit these magic words to memory, and devote yourself to a life of accessors, then Cocoa memory management should cause you no fear.
For those interested in the path to memory management enlightenment, you should first deeply understand every word of the Memory Management Rules. Don’t be afraid, it is very short, and if you will commit it to heart, you will avoid much suffering in the future. Read more…
Because these bugs are very hard to track down and very easy to avoid, I’d like to direct everyone’s attention to how to properly unregister for notifications.
If your object uses NSNotificationCenter ever, you must add the following to -dealloc:
[[NSNotificationCenter defaultCenter] removeObserver:self];
This removes you from all notifications. If you fail to do this, and you are dealloc’ed, and a notification you were observing is later posted, the application will crash with a bizarre access violation deep in NSNotificationCenter when it tries to post to an object (you) which no longer exists. It is tricky to figure out even what notification is being passed in these cases.
If you are not observing anything, then -removeObserver: does nothing, so it is not dangerous to call. There is a slight performance cost, especially for objects that are alloc’ed and dealloc’ed a lot, so there’s no reason to add it to objects that do nothing with notifications, but I recommend better safe than sorry in most cases.
This advice does not apply to KVO observations, which are a completely different animal. Read more…
When faced with the need to return “not found” for something that normally returns an index or other value that would normally be unsigned (whether this is an error condition or a normal event), Cocoa offers the NSNotFound constant as an alternative to returning an illegal index like -1 (which forces you to change the index to an NSInteger, raising the likelihood of sign-based errors if there’s ever a long promotion).
NSNotFound is 0x7fffffff, which is not -1 (0xffffffff), but is still very large (~2 billion) and so should never be a real index for any sanely-sized spaces, and is more readable than -1. NSNotFound is a good constant to remember when these issues come up. Look at NSString -rangeOfString: for an example of its usage.