标签:
NSDictionary
不可变的字典
创建字典的方法
// 创建字典的方式 NSDictionary *dy = [NSDictionary dictionaryWithObject:@"a"forKey:@"b"]; NSDictionary *dy1 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"b",@"c",@"d" ,nil]; // 快速创建字典 // 重复key值,重复的不能保存到字典中 NSDictionary *dy2 = @{@"we":@"haha", @"we":@"ha"}; NSLog(@"%@",dy); NSLog(@"%@",dy1); NSLog(@"%@",dy2);
获取字典的长度
// 获取字典长度 NSDictionary *dy2 = @{@"we":@"haha", @"w":@"ha"}; NSLog(@"%lu",dy2.count); // 输出2 // 如果key值重复,长度不计算在内 NSDictionary *dy2 = @{@"we":@"haha", @"we":@"ha"}; NSLog(@"%lu",dy2.count); //输出1
字典的遍历
NSDictionary *dy1 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"b",@"c",@"d" ,nil]; // 快速创建字典 // 重复key值,重复的不能保存到字典中 NSDictionary *dy2 = @{@"we":@"haha", @"w":@"ha"}; NSLog(@"%lu",dy2.count); // 字典的遍历 for (NSString *key in dy2) { NSLog(@"key = %@, value = %@", key, [dy2 objectForKey:key]); } // 枚举类型遍历 [dy1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"key = %@, value = %@", key, obj); }];
把字典存到文件中
// 把字典保存到文件中 NSDictionary *dy2 = @{@"we":@"haha", @"w":@"ha"}; BOOL isWrite = [dy2 writeToFile:@"/Users/cloudwalk/Desktop/test.plist" atomically:YES]; if (isWrite) { NSLog(@"写入成功"); }
从文件中读取字典
NSDictionary *readDy2 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/cloudwalk/Desktop/test.plist"]; NSLog(@"%@",readDy2);
通过把数组添加到字典中,构建成数组字典
NSArray *sdArr = [NSArray arrayWithObjects:@"zaozhuang",@"jinan",nil]; NSArray *jxArr = [NSArray arrayWithObjects:@"jiujiang",@"nanchang",nil]; NSDictionary *citys = [NSDictionary dictionaryWithObjectsAndKeys:sdArr,@"sd",jxArr,@"jx", nil]; NSLog(@"citys = %@",citys);
NSDictionary *citys = [NSDictionary dictionaryWithObjectsAndKeys:sdArr,@"sd",jxArr,@"jx", nil]; NSLog(@"citys = %@",citys); // 把citys存到文件中 [citys writeToFile:@"/Users/cloudwalk/Desktop/test1.plist" atomically:YES];
Objective-C( Foundation框架 一 NSDictionary)
标签:
原文地址:http://www.cnblogs.com/1023843587qq/p/4799689.html