Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging dictionaries - Incompatible type error

I've been trying to merge two NSDictionaries for a couple hours now. Searched and found that I can use [NSMutableDictionary addEntriesFromDictionary:].

    NSDictionary *areaAttributes = [[area entity] attributesByName];
    NSDictionary *gpsAttributes = [[gps entity] attributesByName];

    NSMutableDictionary *areaAttributesM = [areaAttributes mutableCopy];
    NSMutableDictionary *gpsAttributesM = [gpsAttributes mutableCopy];

    NSMutableDictionary *combinedAttributes =  [areaAttributesM addEntriesFromDictionary:gpsAttributesM];

But I get the error:

Initializing 'NSMutableDictionary *_strong' with an expression of incompatible type 'void'

So this is saying that [areaAttributesM addEntriesFromDictionary:gpsAttributesM] returns void? Is my understanding correct? And why is it returning void?

like image 805
OdieO Avatar asked Jan 14 '13 23:01

OdieO


1 Answers

Yes, you are correct. From the docs:

- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary

As to why, that's simple: Functions that mutate an object in place in Cocoa usually return void, so you can easily distinguish them from functions that return a different object.

Also, there's no reason to mutableCopy the gpsAttributes dictionary; it's just being used as the argument to -[addEntriesFromDictionary:], which doesn't need to be mutable.

So, the right way to do this is:

NSDictionary *areaAttributes = [[area entity] attributesByName];
NSDictionary *gpsAttributes = [[gps entity] attributesByName];

NSMutableDictionary *combinedAttributes = [areaAttributes mutableCopy];
[combinedAttributes addEntriesFromDictionary:gpsAttributes];

You may want to wrap this up in a function (or a method in a category on NSDictionary), if you do if often:

NSDictionary *mergeDictionaries(NSDictionary *lhs, NSDictionary *rhs) {
    NSMutableDictionary *ret = [lhs mutableCopy];
    [ret addEntriesFromDictionary:rhs];
    return ret;
}
like image 110
abarnert Avatar answered Nov 09 '22 03:11

abarnert