數(shù)組,字典對象初始化時,一定要判斷添加的元素是否為nil.否則不是崩潰,就是數(shù)據(jù)和預(yù)期不一致.
NSString *ss = nil;
NSArray *ar = [NSArray arrayWithObjects:@"dsa",ss, @"dsf", nil];
NSLog(@"%@", ar); //雖然不崩潰,但數(shù)據(jù)和預(yù)期不一致
// NSString *a = ar[2]; //由預(yù)期數(shù)據(jù)不一致,導(dǎo)致的數(shù)組越界.
// 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"]; //使用語法糖,對于數(shù)組,里面的元素不能為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); //雖然不崩潰,但數(shù)據(jù)和預(yù)期不一致
/*
*** 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<NSCopying>)#>];
[mD setValue:<#(nullable id)#> forKey:<#(nonnull NSString *)#>];
使用setObject:方法,object不能為nil,而使用setValue方法,object可以為nil.
使用語法糖,對于數(shù)組,里面的元素不能為nil.
使用語法糖,對于字典,key和value都不能為nil.