字典在我们日常开发中也是比较常用的,通过下面的代码我们看一下在ObjC中的字典的常用操作:初始化、遍历、排序
// // main.m // FoundationFramework // // Created by Kenshin Cui on 14-2-16. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // #import <Foundation/Foundation.h> void test1(){ NSDictionary *dic1=[NSDictionary dictionaryWithObject:@"1" forKey:@"a"]; NSLog(@"%@",dic1); /*结果: { a = 1; } */ //常用的方式 NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys: @"1",@"a", @"2",@"b", @"3",@"c", nil]; NSLog(@"%@",dic2); /*结果: { a = 1; b = 2; c = 3; } */ NSDictionary *dic3=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"2", nil] forKeys:[NSArray arrayWithObjects:@"a",@"b", nil]]; NSLog(@"%@",dic3); /*结果: { a = 1; b = 2; } */ //更简单的方式 NSDictionary *dic4=@{@"1":@"a",@"2":@"b",@"3":@"c"}; NSLog(@"%@",dic4); /*结果: { 1 = a; 2 = b; 3 = c; } */ } void test2(){ NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys: @"1",@"a", @"2",@"b", @"3",@"c", @"2",@"d", nil]; NSLog(@"%zi",[dic1 count]); //结果:4 NSLog(@"%@",[dic1 valueForKey:@"b"]);//根据键取得值,结果:2 NSLog(@"%@",dic1[@"b"]);//还可以这样读取,结果:2 NSLog(@"%@,%@",[dic1 allKeys],[dic1 allValues]); /*结果: ( d, b, c, a ),( 2, 2, 3, 1 ) */ NSLog(@"%@",[dic1 objectsForKeys:[NSArray arrayWithObjects:@"a",@"e" , nil]notFoundMarker:@"not fount"]);//后面一个参数notFoundMarker是如果找不到对应的key用什么值代替 /*结果: ( 1, "not fount" ) */ } void test3(){ NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys: @"1",@"a", @"2",@"b", @"3",@"c", @"2",@"d", nil]; //遍历1 for (id key in dic1) {//注意对于字典for遍历循环的是key NSLog(@"%@=%@",key,[dic1 objectForKey:key]); } /*结果: d=2 b=2 c=3 a=1 */ //遍历2 NSEnumerator *enumerator=[dic1 keyEnumerator];//还有值的迭代器[dic1 objectEnumerator] id key=nil; while (key=[enumerator nextObject]) { NSLog(@"%@=%@",key,[dic1 objectForKey:key]); } /*结果: d=2 b=2 c=3 a=1 */ //遍历3 [dic1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"%@=%@",key,obj); }]; /*结果: d=2 b=2 c=3 a=1 */ } void test4(){ NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"a", @"2",@"b", @"3",@"c", @"2",@"d", nil]; [dic removeObjectForKey:@"b"]; NSLog(@"%@",dic); /*结果: { a = 1; c = 3; d = 2; } */ [dic addEntriesFromDictionary:@{@"e":@"7",@"f":@"6"}]; NSLog(@"%@",dic); /*结果: { a = 1; c = 3; d = 2; e = 7; f = 6; } */ [dic setValue:@"5" forKey:@"a"]; NSLog(@"%@",dic); /*结果: { a = 5; c = 3; d = 2; e = 7; f = 6; } */ //注意,一个字典的key或value添加到字典中时计数器+1;字典释放时调用key或value的release一次,计数器-1 } int main(int argc, const char * argv[]) { test1(); test2(); test3(); test4(); return 0; }
注意:同数组一样,不管是可变字典还是不可变字典初始化元素后面必须加上nil以表示结束。