标签:
//创建一个不可变的字典对象
//便利构造器创建
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhonger", @"name2", @"taixu", @"name1", @"caicai", @"name3", nil];
//初始化方法
//先给value 再给key
NSDictionary *dic1 = [[NSDictionary alloc]initWithObjectsAndKeys:@"zhonger", @"name2", @"taixu", @"name1", @"caicai", @"name3", nil];
NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:@[@"name1", @"name2", @"name3"] forKeys:@[@"zhonger", @"name2", @"taixu"]];
//笑笑语法
//key 在前 value在后
NSDictionary *dic3 = @{@"name1":@"zhanger", @"name2":@"caicai", @"name3":@"fufu"};
//获取字典中键值对的个数,以及获取所有的key和所有的value;
NSUInteger count = [dic3 count];
NSArray *arr = [dic3 allKeys];
NSLog(@"dic3 allkeys is %@",arr);
NSLog(@"dic3 allvalue is %@",[dic3 allValues]);
//获取字典中的某个value值,通过key
NSString *string = [dic3 objectForKey:@"name2"];
NSArray *allkeys = [dic3 allKeys];
for (int i = 0; i < [allkeys count]; i ++) {
NSLog(@" %@",[dic3 objectForKey:allkeys[i]]);
}
//创建可变字典对象,初始化方法,便利构造器,字面量
NSMutableDictionary *mDic = [[NSMutableDictionary alloc] initWithCapacity:0];
NSMutableDictionary *mDic1 = [NSMutableDictionary dictionaryWithCapacity:0];
NSMutableDictionary *mDic2 = [@{@"key1":@"zhangsan", @"key2":@"lisi", @"key3":@"wangwu"}mutableCopy];
NSLog(@"mDic2 is %@",mDic2);
//增加键值对的方法 setObject:forkey:
[mDic2 setObject:@"liumazi" forKey:@"key4"];
NSLog(@"mDic2 is %@",mDic2);
//删除键值对的方法,删除之后,key和value都不存在了
//removeObjectForKey:
[mDic2 removeObjectForKey:@"key2"];
NSLog(@"mDic2 is %@",mDic2);
//移除所有的键值对
[mDic2 removeAllObjects];
NSLog(@"mDic2 is %@",mDic2);
//修改键值对的方法和增加键值对的方法是一样的。。
[mDic2 setObject:@"zhangsan" forKey:@"key1"];
NSLog(@"mDic2 is %@",mDic2);
[mDic2 setObject:@"lisi" forKey:@"key1"];
NSLog(@"mDic2 is %@",mDic2);
//字典中的Key是不能重复的 但是value可以重复,并且字典是一个无序集合
Objective - C NSDictionary不可变字典和NSMutableDictionary可变字典
标签:
原文地址:http://www.cnblogs.com/xueyao/p/5193939.html