数组,字典对象添加元素时注意事项

数组,字典对象初始化时,一定要判断添加的元素是否为nil.否则不是崩溃,就是数据和预期不一致.

        NSString *ss = nil;
        
        NSArray *ar = [NSArray arrayWithObjects:@"dsa",ss, @"dsf", nil];
        NSLog(@"%@", ar); //虽然不崩溃,但数据和预期不一致
//        NSString *a = ar[2]; //由预期数据不一致,导致的数组越界.
//        NSLog(@"%@", a);
        
        /*
         *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[1]'
         ***
         */
//        NSArray *sd = @[@"sf", ss, @"fd"]; //使用语法糖,对于数组,里面的元素不能为nil.
//        NSLog(@"%@", sd);
        
        /*
         *** 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?'
         ***
         */
//        NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:@"sd",@"key1",@"sf",ss, @"sds",@"key3", nil];
//        NSLog(@"%@", d);
        
        NSDictionary *d2 = [NSDictionary dictionaryWithObjectsAndKeys:@"sd",@"key1",ss,@"sds", nil];
        NSLog(@"%@", d2); //虽然不崩溃,但数据和预期不一致
        
        /*
         *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[2]'
         ***
         */
        NSDictionary *d3 = @{@"key1":@"sfs", @"key2":@"dsfds", @"key3":ss}; //使用语法糖,对于字典,key和value都不能为nil
        NSLog(@"%@", d3);
       
        NSMutableDictionary *mD = [NSMutableDictionary dictionaryWithCapacity:1];
    NSString *ss = nil;
    mD[@"sf"] = ss; //不会崩溃
    NSLog(@"%@", mD);

        NSMutableDictionary *mD = nil;
        [mD setObject:<#(nonnull id)#> forKey:<#(nonnull id)#>];
        [mD setValue:<#(nullable id)#> forKey:<#(nonnull NSString *)#>];
        使用setObject:方法,object不能为nil,而使用setValue方法,object可以为nil.

使用语法糖,对于数组,里面的元素不能为nil.
使用语法糖,对于字典,key和value都不能为nil.

你可能感兴趣的:(数组,字典对象添加元素时注意事项)