美文网首页
iOS字典对象插入nil的几种报错

iOS字典对象插入nil的几种报错

作者: JxSr程知农 | 来源:发表于2019-08-15 11:19 被阅读0次

### 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);

相关文章

网友评论

      本文标题:iOS字典对象插入nil的几种报错

      本文链接:https://www.haomeiwen.com/subject/emgajctx.html