Flavio Donadio <mailto:fla...@donadio.com.br> wrote (Saturday, May 8, 2010 6:13 AM -0300):

So, in case a class' +init method can return nil and you want to subclass it, 
the code should be more like:

+ (id*)init
{
if ([super init] != nil)
{
...
[return self];
}
else
{
return nil; // or return something else, throw an exception, whatever...
}
}

I am just curious, because I think it's strange to write "self = [super init]" 
anywhere other than in an overriden +init. Am I right?

I'd like to point out that this is one of those counterintuitive cases where more code is less.

The code

    self = [super init];
    if (self!=nil)
        ...

produces fewer machine instructions than

    if ([super init]!=nil)
        ...

Weird, huh?

The compiler can save the instructions needed to preserve |self| before calling [super init] and restoring it afterwards. Anyway, I've disassembled this on several architectures and the code produced by the preferred pattern is shorter, and therefor more efficient, than trying to take a shortcut.

As far as I'm concerned, sticking to the recommended pattern for -init is a win-win.

1) It conforms to the Objective-C conventions
2) It correctly handles all cases of out-of-memory conditions, initializers that fail for any other reason, singleton initializers, and class clusters.
3) It's smaller and faster than any other pattern I've found.
4) It doesn't make assumptions about NSObject, and I can later turn this class into a subclass of something else without having to worry that I've made assumptions that are no longer valid.

So I've yet to find a compelling reason to cheat in -init.



James Bucanek
____________________________________________________________________
Author of Professional Xcode 3                   ISBN: 9780470525227
<http://www.proxcode3.com/>
and Learn Objective-C for Java Developers        ISBN: 9781430223696
<http://objectivec4java.com/>

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to