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 ?
The return option 1 will create an immutable
NSDictionaryobject, 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
NSMutableDictionaryanyways. Casting it to aNSDictionarywill not make any differenceHOWEVER: When calling this method, you will see that it returns an
NSDictionaryand 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.