profile for monkeydom at Stack Overflow, Q&A for professional and enthusiast programmers

cocoa-dom

coding bits I use, come across, like, hate, the whole shebang.

twitter | github | mastodon     rant-dom     rss | archive

Permalink
Home

Choosing the right spot for your task

Usually life with Cocoa is nice. You have hooks and handles for every occasion. However - sometimes you are not looking in the right place, or have no idea this hook you need exists at all.

A strange and interesting example from SubEthaEdit is the [NSAttributedString doubleClickAtIndex:] method. I had to ask for that at WWDC because I was sure this kind of functionality would either be named differently if put at the model level, or would be in NSText or NSTextView. However, there it is, quite misplaced, but there.

Another case of using the right delegate callbacks on the iPhone is the -[UIApplicationDelegate applicationDidFinishLaunching:] method. Coming from the desktop this is a no brainer, this is where you set up your application.

However, with iPhone 3.0 things changed. There now is a new call, -[UIApplicationDelegate application: didFinishLaunchingWithOptions:] which is called in preference of the aforementioned call. This is clearly stated in the UIApplicationDelegate overview in the Documentation. However these are the intricacies you might miss if you are not watchful. Always stay on top of the API changes!

And a last one: Make sure you understand what each hook means. Make sure you put your code in the right spot. Don’t do stuff in -awakeFromNib if there is a better location. E.g. if you are a NSWindowController, -awakeFromNib might get called twice, once for the nib it lives in, once for the nib it itself is loading. Use -windowWillLoad and -windowDidLoad instead. If you are an NSView the -viewWillMoveToSuperview:, -viewDidMoveToSuperview methods may be more suited for setup than the init methods.

Bottom line: make sure you understand the events you get called for and think about if this is the right place to put your code. If not, it is highly likely Cocoa has the right hook for you, you just don’t know it. Think again of what kind of event it is you need do know about and look into the documentation. Don’t forget to look into all notifications as well, some events only trigger those.