On Mon, Nov 3, 2008 at 11:57 AM, j o a r <[EMAIL PROTECTED]> wrote: > > On Nov 3, 2008, at 8:37 AM, Michael Ash wrote: > >> If the method is declared like this then you should assume that you >> get a subclass: >> >> + (id)foo; >> >> And if it is declared like this then you should not assume that: >> >> + (Foo *)foo; >> >> The difference being the return type. The 'id' return type implicitly >> means "this will return whatever is appropriate for the receiver". >> (This should probably be documented better.) The 'Foo *' return type >> tells you only to expect a Foo, and not rely on receiving any sort of >> subclass. >> >> The latter form is rare in Cocoa but shows up in e.g. NSParagraphStyle. > > > My understanding is that that this is the general pattern to use: > > * Return (id) from initializers, and convenience factory methods. > * Return (Foo*) for shared instances. > > There are some exceptions to these "rules" in Cocoa, but they are few and > far in between. > Note that "+[NSParagraphStyle defaultParagraphStyle]" fits this pattern, > since it returns a shared instance.
NSParagraphStyle is a good example of what you're saying, because it would be pretty reasonable for +defaultParagraphStyle to return 'id' and return a new mutable instance when sent to NSMutableParagraphStyle. But instead it returns a shared instance and declares that instance's type. (If you want a mutable object with the default properties, copy the shared instance.) An example of a shared instance with 'id' type is +[NSDocumentController sharedDocumentController]. Here, it's because there's a supported way to subclass NSDocumentController and get your subclass instantiated as the shared instance. In this case, however, the class of the returned object is not necessarily the class of the receiver. An example of a factory method with a static type can be found in NSCharacterSet in 10.4 and below. Turns out this was apparently in error as they got fixed to return 'id' in 10.5 and I believe the release notes state that they can be counted on to return subclass instances on older OSes as well. But absent that change, you'd have to assume that you get a plain NSCharacterSet even when sending those factory messages to, say, NSMutableCharacterSet. Mike _______________________________________________ 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 [EMAIL PROTECTED]