### 1、几种报错信息。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:'*** setObjectForKey: object cannot be nil (key: key1)'
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSDictionary dictionaryWithObjectsAndKeys:]: second object of each pair must be non-nil. Or, did you forget to nil-terminate your parameter list?'
### 2、相关代码。
NSString *value1 = nil;
NSString *value2 = @"value2";
NSString *value3 = @"value3";
NSString *key2 = @"key2";
NSMutableDictionary *mutableDict = @{}.mutableCopy;
[mutableDict setObject:value1 forKey:@"key1"];//会报错。
NSDictionary *dict = @{@"key1":value1, @"key2":value2, @"key3":value3};//会报错。
NSDictionary *dictA = [NSDictionary dictionaryWithObjectsAndKeys:value1, key1, value2, @"key2", value3, @"key3", nil];//不会报错(结果是一个空元素的字典对象)。
NSDictionary *dictB = [NSDictionary dictionaryWithObjectsAndKeys:value2, key2, value3, @"key3", nil];//会报错。
NSLog(@"mutableDict: %@\ndict: %@\ndictA: %@\ndictB: %@\n", mutableDict, dict, dictA, dictB);
网友评论