标签:style io color os ar 使用 for sp strong
NSDictionary :字典是没有顺序的
字典不允许有相同的key,但允许有相同的value
字典的创建方式:
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"jack" forKey:@"Tom"];
NSArray *keys = @[@"name",@"address"];
NSArray *objects = @[@"jack",@"北京"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:
@"jack",@"name",
@"北京",@"address",
nil];
//编译器特性 (推荐使用)
NSDictionary *dict4 = @{@"name":@"jack",@"address":@"北京"};
根据key取出value
id obj1 = [dict1 objectForKey:@"Tom"];
id obj2 = dict2[@"name"];编译器特性,推荐使用
dict1.count:返回的是键值对的个数
NSMutableDictionary:
NSLog(@"%@",@[@"jack",@"rose"]);直接打印集合的话:
(
jack,
rose
)
使用NSLog()打印字典的时候:输出的是:
{
address = "\U5317\U4eac";
name = Rose;
}
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//添加键值对
[dict setObject:@"jack" forKey:@"name"];
[dict setObject:@"北京" forKey:@"address"];
//添加键值对的时候,如果key和已有的相同,那么将会覆盖以前的值
[dict setObject:@"Rose" forKey:@"name"];
//移除键值对
[dict removeObjectForKey:@"name"];
NSString *str = dict[@"name"];
NSLog(@"%@",dict);
遍历字典:
NSDictionary *dict = @{@"address":@"北京",@"name":@"jack",@"QQ":@"12342345t",@"name2":@"jack",@"name3":@"jack"};
获取字典中所有的key
NSArray *keys = [dict allKeys];
for (int i = 0; i < dict.count; i++) {
NSString *key = keys[i];
NSString *object = dict[key];
NSLog(@"%@=%@",key,object);
}
另一种方法:
NSDictionary *dict = @{@"address":@"北京",@"name":@"jack",@"QQ":@"12342345t",@"name2":@"jack",@"name3":@"jack"};
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@-%@",key,obj);
//停止遍历
*stop =YES;
}];
集合总结:
1、NSArray\NSMutableArray
-》有序
-》快速创建(不可变):@[]
-》快速访问元素:集合名[i]
2、NSSet\NSMutableSet
-》无序
3、NSDictionary\NSMutableDictionary
-》无序
-》快速创建(不可变):@{key1:value1,key2:value2。。。。。。}
-》快速访问:字典名[key];
集合中的元素可以是字典
Foundation-06_字典_NSDictionary
标签:style io color os ar 使用 for sp strong
原文地址:http://www.cnblogs.com/yaofch107/p/4055391.html