NSMutableArray * arrayName = [NSMutableArray
array];
NSMutableArray * array = [NSMutableArray
array];
[array removeAllObjects];
for (int i =
0; i< 10; i++) {
NSString * str = [NSString
stringWithFormat:@"name%i",i];
[arrayName
addObject:str];
}
// 方式一
在for循环内初始化字典dict,每次循环都初始化一个新字典,并在循环内加入数组,数组存了10个不同的字典
for (int i =
0; i< 10; i++) {
NSMutableDictionary * dict = [NSMutableDictionary
dictionary];
NSString * value = [NSString
stringWithFormat:@"Female%04i.JPG",i];
NSString * key = arrayName[i];
[dict
setObject:value forKey:key];
[array
addObject:dict];
}
NSLog(@"%@*************",array);
//
方式二 在for循环外初始化字典dict,再循环外初始化可变字典,在循环内每次循环在字典内添加键值对,将存有十个键值对的一个字典赋给数组
NSMutableArray * array2 = [NSMutableArray
array];
NSMutableDictionary * dict2 = [NSMutableDictionary
dictionary];
for (int i =
0; i< 10; i++) {
NSString * value = [NSString
stringWithFormat:@"Female%04i.JPG",i];
NSString * key = arrayName[i];
[dict2
setObject:value forKey:key];
}
[array2
addObject:dict2];
NSLog(@"%@____________",array2);
// 从打印结果可以很清楚的看到两者的区别
// 因为对字典的理解不是很深刻:只是简单地想着他存着键值对,但是他实际可以存n个键值对(若在给可变字典设置键值对前每次都初始化可变字典则每个字典只有一个键值对)
ios给NSMutableDictionary循环赋值的两种方式,在循环内初始化NSMutableDictionary和在循环外初始化NSMutableDictionary有何区别?(已解决)ios给NSMutableDictionary循环赋值的两种方式,在循环内初始化NSMutableDictionary和在循环外初始化NSMutableDictionary有何区别?(已解决)