![](/img/trans.png)
[英]iOS NSMutabledictionary is null when I setValue and forKey
[英]'-setValue:forKey:' exception when updating the fields of an NSMutableDictionary
我有兩個NSMutableDictionary對象,分別稱為“ dict”和newdict。 然后嘗試將newdict分配給“ myfield1”字段。 但是,我遇到了一個錯誤。
NSMutableDictionary *dict = @{ @"myfield1" : @{ @"subfield1" : @"mysubfield1" ,
@"subfield2" : @"mysubfield2" },
@"myfield2": @"myfield2",
@"myfield3": @"myfield3"};
NSMutableDictionary *newdict = @{ @"subfield1" : @"mynewsubfield1" ,
@"subfield2" : @"mynewsubfield2" };
[dict setValue:newdict forKey:@"myfield1"];
錯誤:
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<__NSDictionaryI 0x17db3bb0> setValue:forUndefinedKey:]:
this class is not key value coding-compliant for the key loc.'
我怎么解決這個問題?
不要使用setValue:forKey:
因為這是KVC方法,而不是字典方法。 使用setObject:forKey:
從技術上講,KVC方法會起作用,但是通常只應在有特定需要時才使用它。
真正的問題是字典實例是不可變的。 使用mutableCopy
從文字定義中創建可變版本。 文字定義始終是不可變的。
如@Wain所述,您的字典實例是不可變的。
可能使您感到困惑的是,您將變量聲明為NSMutableDictionary
因此您認為它們將是可變的。 但是@{ … }
文字語法與[NSDictionary dictionaryWithObjects:forKeys:count:
等效,因此創建了一個(非可變的) NSDictionary
實例 。
您將此值影響為NSMutableDictionary
類型的變量的事實不會更改此值,也不會使此字典具有魔術般的可變性。
這就是@Wain正確建議使用mutableCopy
將此NSDictionary
為NSMutableDictionary
以便可以在其上調用setValue:forKey:
或setObject:forKey:
另一種方法是使用[NSMutableDictionary dictionaryWithDictionary:@{ … }];
創建您的可變字典。
實際上,如果-Wincompatible-pointer-types
警告為ON(默認情況下應為ON),則應該有類似warning: incompatible pointer types initializing 'NSMutableDictionary *' with an expression of type 'NSDictionary *'
導致您找到問題的原因及其解決方案。 (始終閱讀警告,不是因為它們僅僅是警告,並且它們不會使編譯失敗,因為它們並不重要!)
只需添加“ mutableCopy”即可使您的字典類型為NSMutableDictionary
NSMutableDictionary *dict = [@{ @"myfield1" : @{ @"subfield1" : @"mysubfield1" ,
@"subfield2" : @"mysubfield2" },
@"myfield2": @"myfield2",
@"myfield3": @"myfield3"} mutableCopy];
NSMutableDictionary *newdict = [@{ @"subfield1" : @"mynewsubfield1" ,
@"subfield2" : @"mynewsubfield2" } mutableCopy];
dict[@"myfield1"]=newdict;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.