On Jun 11, 2008, at 2:01 AM, 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.

I already pointed out that there is *no such thing* as an "NSArray. Period." You are *never* going to get an object whose class is just NSArray. All that -(NSArray *)resultsArray promises is that you're going to get *some* kind of NSArray. An NSMutableArray == an NSArray, by virtue of being a subclass of it.

This is kind of a basic principle of object orientation - a method that returns (Foo *) could give you an object of type Foo. However, it could also give you any random subclass of Foo, because all those qualify as being a Foo, because they are subclasses. All you know about what you're getting is that it will provide the methods that Foo provides, and that you can treat it like a Foo.

A return type of NSArray * means something very explicit. "But all you can expect is an object that behaves like a NSArray, so returning a subclass of NSArray, like NSMutableArray, is perfectly legal!" You're exactly right that all I can expect is an object that behave like a NSArray. /Exactly/ like a NSArray. Not sorta. Not almost. Exactly. Because that's what you explicitly stated. So when the returned array mutates, either because you were sloppy and returned the pointer to your objects internal state, or because during its travels something, somewhere sends it a mutation message inside a @try / @catch block, I'm going to file a bug because whatever it is you returned did not behave like a NSArray. An / immutable/ array.

No, a return type of NSArray doesn't mean it can't be mutable. It does, however, mean that you can't *count* on it being mutable, so if you try to mutate it, the compiler will give you warnings (and the program will throw an exception if the array was not, in fact mutable). You also can't count on it being immutable, because no such promise is given.

If you are storing an array for long-term use and need it absolutely, positively not to mutate while you've got it, then you should be using -[NSArray copy] or perhaps +[NSArray arrayWithArray:] to make yourself a copy of it instead of just hanging onto whatever -(NSArray *)resultsArray gave you.

Charles
_______________________________________________

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]

Reply via email to