let it be

This post explains one of my favorite


categories – one that is extremely universal and handy for shorter and, in my opinion, more memory-manageable code.  (Code below.)

Edit: Commenter David found a bug in this implementation. Check out the fixed version here; the new source files are listed at the bottom of that post. (The fix doesn’t require any change in usage or in the header file, just in the .m file).

The idea is very simple – we can replace code that looks like this:

UIView *view = [[[UIView alloc] initWithFrame:myFrame] autorelease];
MyObject *obj = [[[MyObject alloc] init] autorelease];

with this:

UIView *view = [[UIView be] initWithFrame:myFrame];
MyObject *obj = [MyObject beInit];

As you can guess, we’re basically replacing the


pair with a single method,



Besides giving us much shorter code (more readable, less clutter, friendlier to inlining new objects), this method also encourages use of autoreleased objects.  To really go into why I think this is a good thing, we need another blog post; but I can say briefly that autorelease is the Objective coder’s smart pointer.  It helps the code, not the coder, remember what needs cleaning up.

Without further ado, here’s the extremely simple yet incredibly useful category: