Reputation: 11700
If I have a method that looks something like this:
- (NSDictionary *)removeDataInDictionary:(NSDictionary *)dictionary {
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
[mutableDictionary removeObjectForKey:@"key"];
// Return option 1
return [NSDictionary dictionaryWithDictionary:mutableDictionary];
// Return option 2
return (NSDictionary *) mutableDictionary;
}
Is option 1 "better" codewise because it will really return a NSDictionary
whilst option 2 will actually return a NSMutableDictionary
disguised into a NSDictionary
?
Upvotes: 10
Views: 2795
Reputation: 3937
The return option 1 will create an immutable NSDictionary
object, which is the way to go if you don't want it to be edited by any means.
The return option 2 will return an NSMutableDictionary
anyways. Casting it to a NSDictionary
will not make any difference
HOWEVER: When calling this method, you will see that it returns an NSDictionary
and thus you will have to consider it as such outside, so unless you check the object class and then cast it to an NSMutableDictionary outside your method, it will look immutable outside.
Upvotes: 5