Re: why does this method return an id?
Re: why does this method return an id?
- Subject: Re: why does this method return an id?
- From: Quincey Morris <email@hidden>
- Date: Tue, 13 Dec 2011 00:14:52 -0800
On Dec 12, 2011, at 22:39 , Matt Neuburg wrote:
> But if you subclassed NSSortDescriptor and didn't override sortDescriptorWithKey:ascending: and expected [MyFancyEtc. sortDescriptorEtc.] to magically produce a MyFancyEtc. instead of an NSSortDescriptor, you'd *deserve* that warning. In fact, having that warning would be *good*.
I think the point is that there is a huge (historical) mess here, so you're seeing the fossilized strata of various attempts to deal with it.
There are two equally valid semantic patterns for [SomeSubclass convenieceMethodForANewInstance], where convenieceMethodForANewInstance is implemented in a parent class SomeClass. One returns a SomeSubclass; the other returns a SomeClass. (The difference is [self alloc] vs [SomeClass alloc] in the parent class implementation.) The choice of semantics depends on the needs of the class.
> Why are we turning type checking *off* at a crucial moment like this?
Because if the alternative is casting the return value to the correct subclass, then the cast *also* effectively turns off type checking. Type id is probably slightly superior to a cast in these circumstances.
In the sort descriptor case, it may be that the returns-an-id pattern was chosen by analogy with the NSString/NSMutableString case, except that the subclass was mythical or intended for the future. Or the pattern was just fashionable at the time.
> Also, if that's the right answer (i.e. if it's all about subclassing), then I don't get why *every* convenience constructor isn't typed as an id. Are the counterexamples all things that one is expected never to subclass?
This finally got cleaned up with ARC (or, at least, with the ARC-related new language features). Under newer Clangs, there are "related return types", which are supported by language features such as 'instancetype' or the 'new...' method family. Going forward, this means that either semantic pattern can be represented without the need for an 'id' return type or a cast of the return value, so type checking is viable.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden