In the following code, I don’t get any warning or compile error if I return NSMutableArray instead of NSArray which is the method’s return type.
But is it good practice to convert return value to NSArray by using -copy method like the following code?
Or should I return NSMutableArray?
+(NSArray *)returnImutableArray {
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:@"a"];
[arr addObject:@"b"];
//return arr; // no warning
return [arr copy];
}
I think this is essentially personal preference. You incur a (probably small) performance penalty by copying the array before returning it. The upside is that you’ll completely prevent mutation of the result further down the line. However, I don’t usually go to the trouble. Because the declared return type of the method is an immutable NSArray, the compiler will warn you if you try to call one of NSMutableArray’s mutation methods on it unless you go out of your way to prevent that (by casting to NSMutableArray).
So, in short, it’s personal preference and I personally don’t generally bother with the immutable copy.