【1】字典的创建
//静态方法,不需要释放内存 NSDictionary *dit=[[NSDictionary alloc] init]; NSDictionary *dict=[NSDictionary dictionaryWithObject:@"v" forKey:@"k"]; NSLog(@"%@",dict);
2.
//最常用的初始化方式 dict=[NSDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",nil]; NSLog(@"%@",dict);
3.
NSArray *obkects=[NSArray arrayWithObjects:@"v1",@"v2",@"v3",nil]; NSArray *keys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil]; dict=[NSDictionary dictionaryWithObjects:obkects forKeys:keys]; NSLog(@"%@",dict);
【2】字典的使用
1.
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //count是计算有多少个键值对; NSLog(@"count=%zi",[dict count]);
2.
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //这个是来查看键值的另外一个 //由于NSdictionary是不可变的,所以只能取值,不能修改值 id obj=[dict objectForKey:@"k2"]; NSLog(@"obj=%@",obj);
3.将字典写入文件中
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; NSString *path=@"/Users/haiyefeng/Desktop/test.txt"; [dict writeToFile:path atomically:YES];
4.
//读取文件中的字典。 NSString *path2=[NSDictionary dictionaryWithContentsOfFile:path]; NSLog(@"%@",path2);
【3】字典的用法2
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; NSArray *key= [dict allKeys]; NSLog(@"keys=%@",key);
2.
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; NSArray *objects=[dict allValues]; NSLog(@"%@",objects);
3.
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; objects= [dict objectsForKeys:[NSArray arrayWithObjects:@"k1",@"k2",@"k555",nil] notFoundMarker:@"not found"];//notfoundmarker里如果找不到的话,当key找不到对应的value时,用maker参数值代替 NSLog(@"objects=%@",objects);
【4】遍历字典
void dictFot(){ NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //遍历字典的所有key for(id key in dict){ id value =[dict objectForKey:key]; NSLog(@"%@",value); } }
2.迭代器
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //key 迭代器 NSEnumerator *enumer=[dict keyEnumerator]; id key =nil; while (key=[enumer nextObject]){ id value =[dict objectForKey:key]; NSLog(@"%@=%@",key,value); }
3.这里只提供方法
//对象迭代器 //[dict objectEnumerator];
4.
//遍历字典3 void dictFor3(){ NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; [dict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) { NSLog(@"%@=%@",key,obj); }]; }