// // main.m // nsdictionary // // Created by 裴烨烽 on 14-1-31. // Copyright (c) 2014年 裴烨烽. All rights reserved. // #import <Foundation/Foundation.h> // nsdictionary//根据某个索引,然后找到这个内容 //这个也是不可变数组 void dictCreate(){ //字典的创建 //静态方法,不需要释放内存 NSDictionary *dit=[[NSDictionary alloc] init]; NSDictionary *dict=[NSDictionary dictionaryWithObject:@"v" forKey:@"k"]; NSLog(@"%@",dict); //最常用的初始化方式 dict=[NSDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",nil]; NSLog(@"%@",dict); NSArray *obkects=[NSArray arrayWithObjects:@"v1",@"v2",@"v3",nil]; NSArray *keys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil]; dict=[NSDictionary dictionaryWithObjects:obkects forKeys:keys]; NSLog(@"%@",dict); } //字典基本使用 void dictUse(){ NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; //count是计算有多少个键值对; NSLog(@"count=%zi",[dict count]); //这个是来查看键值的另外一个 //由于NSdictionary是不可变的,所以只能取值,不能修改值 id obj=[dict objectForKey:@"k2"]; NSLog(@"obj=%@",obj); //将字典写入文件中 NSString *path=@"/Users/haiyefeng/Desktop/test.txt"; [dict writeToFile:path atomically:YES]; //读取文件中的字典。 NSString *path2=[NSDictionary dictionaryWithContentsOfFile:path]; NSLog(@"%@",path2); } //字典的用法 void dictUse2(){ NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: @"v1",@"k1", @"v2",@"k2", @"v3",@"k3",nil]; NSArray *key= [dict allKeys]; NSLog(@"keys=%@",key); //查看所有的values; NSArray *objects=[dict allValues]; NSLog(@"%@",objects); //根据很多个键,找出很多个值value objects= [dict objectsForKeys:[NSArray arrayWithObjects:@"k1",@"k2",@"k555",nil] notFoundMarker:@"not found"];//notfoundmarker里如果找不到的话,当key找不到对应的value时,用maker参数值代替 NSLog(@"objects=%@",objects); } //遍历字典 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); } } //遍历字典,通过迭代器 void dictFot2(){ 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); } //对象迭代器 //[dict objectEnumerator]; } //遍历字典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); }]; } int main(int argc, const char * argv[]) { @autoreleasepool { //dictCreate(); // dictUse2(); dictFor3(); } return 0; }