Re: Garbage collector vs variable lifetime
Re: Garbage collector vs variable lifetime
- Subject: Re: Garbage collector vs variable lifetime
- From: Graham Cox <email@hidden>
- Date: Wed, 11 Jun 2008 17:35:52 +1000
On 11 Jun 2008, at 5:01 pm, John Engelhart wrote:
If you declare a method prototype as '-(NSArray *)resultsArray',
then you have explicitly communicated that a NSArray is going to be
returned. Not a NSMutableArray. Not 'Jimmies groovy array with red
pin stripes'. A NSArray. Period. A NSMutableArray != a NSArray.
If you're going to be returning (or accepting) more than a single
class, you use id, which clearly communicates your intentions.
That's not the case.
A NSMutableArray is not *LIKE* an NSArray, it *IS* an NSArray - it
implements everything that NSArray does, plus some additional stuff of
its own, so if you return an NSMutableArray from a method returning
NSArray*, you are not breaking any contracts. This is actually common.
In fact, it's a key benefit/feature of *all* object-oriented
programming. Of course you have to know that NSMutableArray is a
subclass of NSArray, or indeed it wouldn't be correct to do this.
However, this is clearly stated in the docs and also easily
discoverable. There are other objects that you can't use this way -
for example NSAttributedString is not a subclass of NSString.
id is only used in circumstances where a stronger type can't be used.
In fact I generally avoid it except where absolutely necessary. It's
usually used to mean unrelated classes can be substituted, or where a
stronger type can cause access problems, as in your example of array =
[NSMutableArray array]; Having invoked that class method, you want to
be able to call NSMutableArray-specific methods on it. If it returned
type NSArray*, you couldn't do so without a cast.
G.
_______________________________________________
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