A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

NSDictionary的创建
+(instancetype)dictionary
+(instancetype)dictionaryWithObject:(id)object forKey:(id<NSCopying>) key;//objectForKey根据键取值
+(instancetype)dictionaryWithObjectsAndKeys:(id)firstObject,...;
一组键值对
NSDictionary *dict2=[NSDictionary dictionaryWithObject:@"张三" forKey:@"zs");


多组键值对
NSDictionary *dict2=[NSDictionary dictionaryWithObjectsAndKeys:@"张三",@"zs",@"value2",@"k2",nil);


输出 zs=zhangsan


字典的key和value都必须是对象


快速创建一个字典


@{,key值:value值,};


NSDictionary *dict4=@{@"zs":@"zhangsan ",@"ls":@"lisi"};


特点
1. key值不能重复
2.键值对存储的数据是无序的
3.键值对集合可以根据键快速取数据




-(NSUInteger)count;返回字典的键值对数目
-(id)objectForKey:(id)aKey;根据key取出value






字典的遍历


for循环遍历字典默认获取的是key值


for(NSString *key in dict4)
{
NSLog(@"%@%@",key,[dect4 objectForKey:key]);
}


key valuestop
dict4 enumrateKeysAndObjectsUsingBlock:^(id key,id obj,BOOL *stop)
{
NSLog(@"%@%@",key,obj);
}






NSDictionary的简写形式
@{};


NSDictionary获取元素


dict[@"name"];



NSDictionary文件操作


将字典写入文件中
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
-(BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically;


NSDictionary *readDict=[NSDictionary dictionaryWithContentsOfFile:@"路径"];




NSArray *lnArr = [NSArray arrayWithObjects:@"dalian ","shenyang",nil];
NSArray *hbArr=[NSArray arrayWithObjects:@"baoding",@"shijiazhuang",nil];


NSDictionary *citys=[NSDictionary dictionaryWithObjectsAndKeys:lnarr,@"ln",hbarr,@"hb",nil];


[citys writeToFile:@"路径/citys.plist" atomically:YES];








NSDictionary *cityDict=[NSDictionary dictionaryWithContentsOfFile:@"路径/citys.plist"];
[citysDict enumerateKeyAndObjectsUsingBlock:^(id key,id obj,BOOL *stop){


for(NSString *str in obj){
NSLog(@"%@",str);
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马