![](/img/trans.png)
[英]Objective-C throws NSInvalidArgumentException with Dictionaries & Arrays
[英]Objective-C: Static NSDictionary throws NSInvalidArgumentException when I add to it
我有一種方法,應該采用NSManagedObject,將其屬性復制到字典中,然后將字典添加到具有NSManagedObjectID鍵的靜態NSMutableDictionary中的NSMutableArray。 問題是,當我嘗試添加到靜態NSMutableDictionary時,它崩潰了,並且僅當我現場制作一個時才起作用。
該問題肯定與靜態NSMutableDictionary更改有關,因為如果我使用非靜態字典,則不會得到異常。 定義如下(在@implementation上方):
static NSMutableDictionary* changes = nil;
這是方法:
+ (void)acceptChange: (NSManagedObject *)change{
if (!changes){
NSLog(@"Making new changes dicitonary"); //it prints this when I run
changes = [[NSDictionary alloc] init];
}
NSManagedObjectID* objectID = change.objectID;
NSMutableArray* changeArray = [changes objectForKey: objectID];
bool arrayDidNotExist = NO;
if (!changeArray){
changeArray = [[NSMutableArray alloc] init];
arrayDidNotExist = YES;
}
[changeArray addObject: [(this class's name) copyEventDictionary: change]]; //copies the NSManagedObject's attributes to an NSDictionary, assumedly works
if (arrayDidNotExist) [changes setObject: changeArray forKey: objectID];//throws the exception
//If I do the exact same line as above but do it to an [[NSMutableDictionary alloc] init] instead of the static dictionary changes, it does not throw an exception.
if (arrayDidNotExist) NSLog(@"New array created");
NSLog(@"changeArray count: %d", changeArray.count);
NSLog(@"changes dictionary count: %d", changes.count);
}
確切的異常消息是這樣的:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0xa788e30'
使用NSMutableDictionary
而不是NSDictionary
。 您正在獲得例外,因為, NSMutableDictionary可以動態修改,而NSDictionary無法。 。
NSMutableDictionary
是NSDictionary
子類。 因此,可以通過NSMutableDictionary
對象訪問NSDictionary
所有方法。 此外, NSMutableDictionary
還添加了補充方法來動態修改事物,例如setObject:forKey:
方法setObject:forKey:
編輯
您已使用NSDictionary
而不是`NSMutableDictionary對其進行了初始化。
if (!changes){
NSLog(@"Making new changes dicitonary"); //it prints this when I run
//changes = [[NSDictionary alloc] init];
^^^^^^^^^^^^^^ ------------------> Change this.
changes = [[NSMutableDictionary alloc] init];
}
[__NSDictionaryI setObject:forKey:]
顯示您的字典是不可變的。 您實際上是將字典初始化為不可變的。 這就是為什么它在添加對象時引發異常的原因。
在這里更改此行:
if (!changes){
....
changes = [[NSDictionary alloc] init];
}
至:
if (!changes){
....
changes = [[NSMutableDictionary alloc] init];
}
您已將字典聲明為NSMutableDictionary,因此在編譯時,該字典為NSMutable字典,但是在運行時,它是NSDictionary,因為您將其分配為NSDictionary,無法對其進行更改,因此是例外。 請將字典定義為:-
更改= [[NSMutableDictionary分配]初始化];
如果您閱讀了有關異常的說明,則說明的是同一件事。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.