Tuesday, June 24, 2008

NSObject+CleanupAwareness

To the risk of boring to death my single reader (sorry Usman!), let's continue a bit on the subject of exception :-P Thanks to Objective-C support for categories, it is possible to add shortcut methods to the ubiquitous NSObject class, so that any instantiation of a derived class (virtually any classes of Cocoa) can push and pop itself on/from an existing cleanup stack. And how do we get around of doing that you may ask? Well simply by creating a category of the class:
@interface NSObject (CleanupAwareness)

- (void) pushForCleanupL;

- (void) popFromCleanupL;

@end
The implementing it as follow:
@implementation NSObject (CleanupAwareness)

- (void) pushForCleanupL {

[[HZCleanupStack current] pushL:self];

}

- (void) popFromCleanupL {

[[HZCleanupStack current] popL:self];

}

@end
Then Objective-C will work its magic and any code linked to yours will have it's objects capable of being placed on our cleanup stack. Cool stuff isn't it? At first I wasn't too much excited by Objective-C (its syntax was a little odd for a C++ monkey like myself), but it have definitely grow on me as I got to known it better :-)

If you are, like myself, dying to see the next Pixar movie (this Friday!), be sure to read the review written by (darn) lucky Scott Stevenson on his blog. While you are had it, you may want to also read all the good material that he have written about Cocoa & Objective-C on Cocoa Dev Central.

No comments: