views:

238

answers:

4

I want to create a method that can take an NSMutableArray or an NSArray object.

I think I can just use (id) as the parameter type... or convert the NSArray to NSMutableArray before passing. However I'm not really happy with these solutions.

In other languages I might pass an IList or some shared object that they both inherit from...

I need to enumerate through the array in my method.

What is the way people would typically do this in objective c?

+15  A: 

Take NSArray. NSMutableArray derives from NSArray, so as long as you're only using the NSArray members (such as read-only enumeration), you'll be safe.

Relevant documentation (from Apple's developer site):

John Rudy
indeed, that's what I would do in fact
Gregory Pakosz
This is an actual thing called the Liskov substitution principle — any place you can use a type, you should be able to use one of its subtypes. So any function taking an NSObject (such as the `retain` and `release` methods) can take an NSString, a function taking an NSString can take an NSMutableString, and so on. In fact, the NSArrays you use are *never* direct instances of NSArray — they're actually instances of a private subclass, and it "just works" because of the substitution principle.
Chuck
+2  A: 

Use NSArray* -- NSMutableArray inherits from it and you can iterate both as if they were NSArrays.

fbrereto
+5  A: 

Since NSMutableArray is a subclass of NSArray, just have your method take an NSArray parameter. That way, it will take anything that is or is a subclass of NSArray.

Matt Ball
A: 

I would stick with NSArray as the parameter because I prefer to use immutable objects wherever possible (looser coupling), and then use the -mutableCopy method when required to send them to an to a function that needs to modify the array.

Abizern