Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How careful are you with your return types in Objective-C?

Say you have a method that returns a newly generated NSArray instance that is built internally with an NSMutableArray. Do you always do something like this:

- (NSArray *)someArray {
    NSMutableArray *mutableArray = [[NSMutableArray new] autorelease];
    // do stuff...
    return [NSArray arrayWithArray:mutableArray];  // .. or [[mutableArray copy] autorelease]
}

Or do you just leave the mutable array object as-is and return it directly because NSMutableArray is a subclass of NSArray:

- (NSArray *)someArray {
    NSMutableArray *mutableArray = [[NSMutableArray new] autorelease];
    // do stuff...
    return mutableArray;
}

Personally, I often turn a mutable array into an NSArray when I return from methods like this just because I feel like it's "safer" or more "correct" somehow. Although to be honest, I've never had a problem returning a mutable array that was cast to an NSArray, so it's probably a non-issue in reality - but is there a best practice for situations like this?

like image 387
Sean Avatar asked Sep 22 '09 21:09

Sean


People also ask

What is the default return type in Objective-C?

(id) is the default return type if none is given.

Is Objective-C type safe?

Objective C objects are completely "type safe". They are actually true objects in that they can receive and potentially handle any message sent to them. This is an advanced but powerful feature and is in fact exactly what Dr Alan Kay meant when he coined the term "Object Oriented".

What does @() mean in Objective-C?

In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals. '@' is used a lot in the objective-C world.

Why does Objective-C use yes and no?

It's just syntax, there's no technical reason for it. They just use YES/NO for their BOOL instead of true/false like c++ does.


2 Answers

I used to do the return [NSArray arrayWithArray:someMutableArray], but I was slowly convinced that it doesn't offer any real benefit. If a caller of your API is treating a returned object as a subclass of the declared class, they're doing it wrong.

[NB: See bbum's caveat below.]

like image 173
Wevah Avatar answered Sep 21 '22 09:09

Wevah


It's very common to return an NSMutableArray cast as an NSArray. I think most programmers would realize that if they downcast an immutable object and mutate it, then they're going to introduce nasty bugs.

Also, if you have an NSMutableArray ivar someMutableArray, and you return [NSArray arrayWithArray:someMutableArray] in a KVC accessor method, it can mess up KVO. You'll start getting "object was deallocated with observers still attached" errors.

like image 30
Tom Dalling Avatar answered Sep 22 '22 09:09

Tom Dalling