標籤:
//建立一個不可變的字典對象
//便利構造器建立
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可變字典