Peter Warbo
Peter Warbo

Reputation: 11700

Objective-c return method returning NSMutableArray instead of declared NSArray return type

If I want to return an immutable array like this + (NSArray *)ids but inside this method I'm declaring a NSMutableArray because I want to sort it using -sortUsingSelector:.

Returning this method works perfect.

Upvotes: 8

Views: 2599

Answers (2)

uvesten
uvesten

Reputation: 3355

  • Whether it's "okay" or not is a difficult question. If it's a small project and only you use the code, it might be allright. However, if you rely on nothing being able to change the "NSArray" returned, it's not ok. (See the last point)

  • Yes.

  • It's an NSMutableArray. A simple cast will let you change the values in it.

If you actually want to a return an immutable object, do the following:

  NSArray* immutableArray = [[mutableArray copy] autorelease];
  return immutableArray;

Upvotes: 2

user557219
user557219

Reputation:

(…) is it "okay" to write code that declares that the return method should be one type and the actualy type is another?

Yes, it is provided the types are compatible; see the next paragraph. In fact, there are some cases in Cocoa (notably class clusters) that do that as well.

Does this work because NSMutableArray is a subclass of NSArray?

Exactly. Since NSMutableArray is a subclass of NSArray, it inherits all its methods and declared properties, so it publicly behaves like NSArray. This is called the Liskov substitution principle.

Is the actual return value a NSArray or a NSMutableArray?

The return value is whatever you’re returning. Since you’re returning an NSMutableArray, it’s an NSMutableArray. From the caller perspective, it is an object that can be used like an NSArray.

Upvotes: 6

Related Questions