我一直试图将两个NSDictionaries合并几个小时.搜索并发现我可以使用[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];
但我得到错误:
Initializing 'NSMutableDictionary *_strong' with an expression of incompatible type 'void'
所以这就是说[areaAttributesM addEntriesFromDictionary:gpsAttributesM]返回void?我的理解是否正确?为什么它回归无效?
解决方法
是的,你是对的.从
the docs开始:
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary
至于为什么,这很简单:在Cocoa中改变对象的函数通常返回void,因此您可以轻松地将它们与返回不同对象的函数区分开来.
此外,没有理由对gpsAttributes字典进行mutableCopy;它只是被用作 – [addEntriesFromDictionary:]的参数,它不需要是可变的.
所以,正确的方法是:
NSDictionary *areaAttributes = [[area entity] attributesByName]; NSDictionary *gpsAttributes = [[gps entity] attributesByName]; NSMutableDictionary *combinedAttributes = [areaAttributes mutableCopy]; [combinedAttributes addEntriesFromDictionary:gpsAttributes];
如果您经常这样做,您可能希望将其包装在函数(或NSDictionary上的类别中的方法)中:
NSDictionary *mergeDictionaries(NSDictionary *lhs,NSDictionary *rhs) { NSMutableDictionary *ret = [lhs mutableCopy]; [ret addEntriesFromDictionary:rhs]; return ret; }