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

Let's say I create a subclass of NSObject (let's call it "MyOddObject") and 
override its -init method:

- (id)init
{
self = [super init];
// blah blah blah ...
return self; // return type will be NSObject!!
}

And then I instantiate this class afterwards:

MyOddObject* myOddInstance = [[MyOddObject alloc] init];

I should get an instance of MyOddObject, but I am getting a NSObject instead.

No, you'll get an instance of MyOddObject. The type (class) of an object is established by +alloc. So the (uninitialized) object returned by [MyOddObject alloc] is already an instance of MyOddObject. No -init method, or any other method for that matter, will ever change this[1].

All right, I think the above line also casts the return value to MyOddObject. Am I right?

Casting never affects the class of an object at runtime. In Objective-C, casting only changes the assumptions made by the compiler at compile time.

My question is: apart from the optimization advantages cited by James Bucanek,
why would one set self's value to the return value of [super init]? Wouldn't
it be confusing?

The main reason is when dealing with subclasses of other classes. Classes can override their -init method to implement singletons, object pools, and class clusters. What happens is this:

1) You allocate a new object with +alloc.

2) The object is sent an -init method (-[MyOddObject init])

3) Your -init code starts by sending [super init].

4) The superclass decides to implement a singleton, object pool, or class cluster. It destroys the nascent object you created in step 1 and obtains a new object pointer. This new object pointer might be a shared singleton object, it might be a pre-constructed object from an object pool, or it could be new object with a different class. It initializes this new object and returns it to your code.

5) Your code assigns the returned object point to self (self=[super init]).

Now the rest of the code in your -init method will be acting on the object returned by [super init], not the object originally created in step 1, which has likely been destroyed already.

James

[1] Technically that isn't true. Isa swizzling can dynamically alter the class of an object later in its life, but that's nitpicking that the nitpickers will mindlessly try to pick, so this footnote is intended to cut them off before they get started.

--
James Bucanek

_______________________________________________

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