Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Class methods: [self alloc] vs. [[self class] alloc]?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Class methods: [self alloc] vs. [[self class] alloc]?



Hi. I'm an objective-c newbie, and I have a question about a point mentioned in Apple's documentation:
http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/ LanguageOverview/chapter_4_section_6.html#//apple_ref/doc/uid/ 20001424-BAJHIAGB


The end of the section says, "In fact, rather than sending the alloc message to self in a class method, it’s often better to send alloc to [self class]. This way, if the class is subclassed, and the rectangleOfColor: message is received by a subclass, the instance returned will be the same type as the subclass." They list a GOOD version and an EXCELLENT version of the rectangleOfColor: class method. The only difference is that the GOOD version does "id newInstance = [[self alloc] init];", while the EXELLENT version does "id newInstance = [[[self class] alloc] init];".

I'm hoping that someone can explain this point to me, because I can't seem to wrap my mind around it. I don't see why there would be a difference between the two versions. It seems to me that [self class] would return the same object that self points to, namely, your subclass object. After all, self should point to the same object in either version of the method (when the receiver is the subclass). If self didn't point to the subclass object in the GOOD version (suppose, for example, that it pointed to the subclass's superclass, which contains the definition of the rectangleOfColor: method), then [self class] wouldn't return the correct object in the EXCELLENT version. Moreover, if [self alloc] created an instance of the superclass rather than of the subclass, then the GOOD method would actually be disastrous, not just less than excellent, because you'd eventually be trying to assign values to non-existent instance variables of the subclass.

I'd appreciate any clarification here.  Thanks!

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden




Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.