12-7 NSDictionary
原文:http://rypress.com/tutorials/objective-c/data-types/nsdictionary
NSDictionary
如同NSSet,NSDictionary类也是描述对象无序数据集;然而,但是由于有key的存在可以使得key和对象一一对应。

The basic collection classes of the Foundation Framework
NSDictionary是不可变的,但是NSMutableDictionary可以动态的增加好删除数据,是可变的。
创建不可变字典
不可变字典可以使用 @{}的语法来创建,也可以使用dictionaryWithObjectsAndKeys: 和dictionaryWithObjects:forKeys:方法进行创建,详见下述:
// Literal syntax
NSDictionary *inventory = @{
],
],
],
],
};
// Values and keys as arguments
inventory = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:], @"Mercedes-Benz SLK250",
[NSNumber numberWithInt:], @"Mercedes-Benz E350",
[NSNumber numberWithInt:], @"BMW M3 Coupe",
[NSNumber numberWithInt:], @"BMW X6", nil];
// Values and keys as arrays
NSArray *models = @[@"Mercedes-Benz SLK250", @"Mercedes-Benz E350",
@"BMW M3 Coupe", @"BMW X6"];
NSArray *stock = @[[NSNumber numberWithInt:],
[NSNumber numberWithInt:],
[NSNumber numberWithInt:],
[NSNumber numberWithInt:]];
inventory = [NSDictionary dictionaryWithObjects:stock forKeys:models];
NSLog(@"%@", inventory);
dictionaryWithObjectsAndKeys:方法把键值对作为参数,所以每两个参数最为一个键值对。这样的排列显得很不直观,并且需要值在前键在后。dictionaryWithObjects:ForKeys:方法使用起来相对直观和简单一下,但是你要特别注意,键值的数组长度必须保持一致。
在平时我们可能使用NSString来做key,但是其实只要实现了NSCopying协议并且实现了hash和isEqual:方法的对象都可以做key。这是因为作为key的话其实会拷贝原值,而作为值的对象通常采用强引用的方式(这一点和set以及array一样)。
访问 Values and Keys
你可以使用像arrays一样的下标的方式进行(someDict[key])某个key下value的读取。objectForKey:方法是另外一个比较常用的获取数据的方式。
NSDictionary *inventory = @{
],
],
],
],
};
NSLog(@"There are %@ X6's in stock", inventory[@"BMW X6"]);
NSLog(@"There are %@ E350's in stock",
[inventory objectForKey:@"Mercedes-Benz E350"]);
一般我们都是按照上述方式进行数据的读取的;然而我们也可以使用allKeysForObject:反过来查询。注意这个方法返回的是一个数组因为会有多个key下的value是一样的。例如下面的例子。
NSDictionary *inventory = @{
],
],
],
],
};
NSArray *outOfStock = [inventory allKeysForObject:
[NSNumber numberWithInt:]];
NSLog(@"The following cars are currently out of stock: %@",
[outOfStock componentsJoinedByString:@", "]);
枚举字典
如同sets和arrays一样快速枚举是去枚举字典的高效的方式,它通过key来循环访问整个字典。NSDictionary同样也提供了count方法来返回整个字典中存储的键值对。
NSDictionary *inventory = @{
],
],
],
],
};
NSLog(@"We currently have %ld models available", [inventory count]);
for (id key in inventory) {
NSLog(@"There are %@ %@'s in stock", inventory[key], key);
}
你可以使用allKeys/allValues方法来讲字典的键值分离,并且这两个方法都返回对应key和value的数组,并且顺序是按照键值对一一对应的。
NSLog(@"Models: %@", [inventory allKeys]); NSLog(@"Stock: %@", [inventory allValues]);
还有一种以块方式枚举的方式:
[inventory enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"There are %@ %@'s in stock", obj, key);
}];
字典比较
字典的比较和数组的比较一样的。当比较的字典一样(键值对和键值对数目都一样)的时候isEqualToDictionary:方法返回YES。
NSDictionary *warehouseInventory = @{
],
],
],
],
};
NSDictionary *showroomInventory = @{
],
],
],
],
};
if ([warehouseInventory isEqualToDictionary:showroomInventory]) {
NSLog(@"Why are we storing so many cars in our showroom?");
}
字典keys的排序
字典无法排序到一个新的实例中,但是能够通过keysSortedByValueUsingComparator:方法来对key进行排序。
NSDictionary *prices = @{
@"Mercedes-Benz SLK250" : [NSDecimalNumber decimalNumberWithString:@"42900.00"],
@"Mercedes-Benz E350" : [NSDecimalNumber decimalNumberWithString:@"51000.00"],
@"BMW M3 Coupe" : [NSDecimalNumber decimalNumberWithString:@"62000.00"],
@"BMW X6" : [NSDecimalNumber decimalNumberWithString:@"55015.00"]
};
NSArray *sortedKeys = [prices keysSortedByValueUsingComparator:
^NSComparisonResult(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
NSLog(@"%@", sortedKeys);
需要注意的是字典的值被作为参数穿入口块而非key本身,其实你也可以对allkeys河allValues进行排序来达到目的。
过滤字典键
同样的,你不能直接过滤一个字典,但是keysOfEntriesPassingTest:方法来进行过滤,如下:
NSDictionary *prices = @{
@"Mercedes-Benz SLK250" : [NSDecimalNumber decimalNumberWithString:@"42900.00"],
@"Mercedes-Benz E350" : [NSDecimalNumber decimalNumberWithString:@"51000.00"],
@"BMW M3 Coupe" : [NSDecimalNumber decimalNumberWithString:@"62000.00"],
@"BMW X6" : [NSDecimalNumber decimalNumberWithString:@"55015.00"]
};
NSDecimalNumber *maximumPrice = [NSDecimalNumber decimalNumberWithString:@"50000.00"];
NSSet *under50k = [prices keysOfEntriesPassingTest:
^BOOL(id key, id obj, BOOL *stop) {
if ([obj compare:maximumPrice] == NSOrderedAscending) {
return YES;
} else {
return NO;
}
}];
NSLog(@"%@", under50k);
NSMutableDictionary
可变字段可以动态的增删键值对。可变字典的增删和可变sets的增删效率差不多,需要注意的是如果需要对数据频繁增删则这两种数据结构在效率上优先于arrays。
创建可变字典
可变字典可以同样可以使用不可变字典中的工厂方法创建,但是很多这些方法并不直观,所以你可以使用dictionaryWithDictionary:方法进行一个直观的转换:
NSMutableDictionary *jobs = [NSMutableDictionary
dictionaryWithDictionary:@{
@"Audi TT" : @"John",
@"Audi Quattro (Black)" : @"Mary",
@"Audi Quattro (Silver)" : @"Bill",
@"Audi A7" : @"Bill"
}];
NSLog(@"%@", jobs);
增加和删除键值对
setObject:forKey: 和 removeObjectForKey:方法可以增加修改和删除键值对。当然你甚至可以只要使用下标的方式直接修改(增加或者修改)键值对。
NSMutableDictionary *jobs = [NSMutableDictionary
dictionaryWithDictionary:@{
@"Audi TT" : @"John",
@"Audi Quattro (Black)" : @"Mary",
@"Audi Quattro (Silver)" : @"Bill",
@"Audi A7" : @"Bill"
}];
// Transfer an existing job to Mary
[jobs setObject:@"Mary" forKey:@"Audi TT"];
// Finish a job
[jobs removeObjectForKey:@"Audi A7"];
// Add a new job
jobs[@"Audi R8 GT"] = @"Jack";
合并字典
可变字典可以使用addEntriesFromDictionary:方法来加载另外一个字典进行扩展。例如:
NSMutableDictionary *jobs = [NSMutableDictionary
dictionaryWithDictionary:@{
@"Audi TT" : @"John",
@"Audi Quattro (Black)" : @"Mary",
@"Audi Quattro (Silver)" : @"Bill",
@"Audi A7" : @"Bill"
}];
NSDictionary *bakerStreetJobs = @{
@"BMW 640i" : @"Dick",
@"BMW X5" : @"Brad"
};
[jobs addEntriesFromDictionary:bakerStreetJobs];
这个方法也可以作为创建可变字典的一个方式:
// Create an empty mutable dictionary
NSMutableDictionary *jobs = [NSMutableDictionary dictionary];
// Populate it with initial key-value pairs
[jobs addEntriesFromDictionary:@{
@"Audi TT" : @"John",
@"Audi Quattro (Black)" : @"Mary",
@"Audi Quattro (Silver)" : @"Bill",
@"Audi A7" : @"Bill"
}];
注意事项
字典在被迭代的时候不能修改。
使用allKeys or allValues或者键值的嘴阀并不直观,尽可能使用dictionaryWithDictionary: 类方法去创建一个克隆一个字典去处理。
12-7 NSDictionary的更多相关文章
- NSDictionary所有API的学习。
<欢迎大家增加iOS开发学习交流群:QQ529560119> @property (readonly)NSUInteger count; //1.利用指定的key寻找相应的value - ...
- Xcode 7.0 SDK(Software Development Kit) 及 Sandbox(沙盒) 存放路径
1. Sandbox(沙盒) 存放路径 我的硬盘/Users/wj121/Library/Developer/CoreSimulator/Devices/879D7E35-BE50-4620-97E1 ...
- python 各模块
01 关于本书 02 代码约定 03 关于例子 04 如何联系我们 1 核心模块 11 介绍 111 内建函数和异常 112 操作系统接口模块 113 类型支持模块 114 正则表达式 115 语言支 ...
- Python Standard Library
Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...
- 在mybatis中写sql语句的一些体会
本文会使用一个案例,就mybatis的一些基础语法进行讲解.案例中使用到的数据库表和对象如下: article表:这个表存放的是文章的基础信息 -- ------------------------- ...
- Fouandation(NSString ,NSArray,NSDictionary,NSSet) 中常见的理解错误区
Fouandation 中常见的理解错误区 1.NSString //快速创建(实例和类方法) 存放的地址是 常量区 NSString * string1 = [NSString alloc]init ...
- 一些NSArray,NSDictionary,NSSet相关的算法知识
iOS编程当中的几个集合类:NSArray,NSDictionary,NSSet以及对应的Mutable版本,应该所有人都用过.只是简单使用的话,相信没人会用错,但要做到高效(时间复杂度)精确(业务准 ...
- OC 解决NSArray、NSDictionary直接打印中文出现乱码的问题
在iOS开发中,经常需要查看数组中得元素是否是自己想要的,但是苹果并没有对直接打印数组中得中文作处理,直接打印就会出现一堆很讨厌的东西,解决其实很简单,就是需要通过为NSArray添加分类,重写 - ...
- iOS - OC NSDictionary 字典
前言 @interface NSDictionary<__covariant KeyType, __covariant ObjectType> : NSObject <NSCopyi ...
- [示例]NSDictionary编程题-字典的排序应用(iOS4班)
代码: #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepo ...
随机推荐
- 【题解】SDOI2009Bill的挑战
这题好像状压的做法比较的无脑?但想记录一下容斥的做法,感觉自己对于容斥简直一无所知.这道题目容斥的解法我也是看了题解才会的.如有雷同,是我看的(*/ω\*)我们可以首先枚举当前字符串与给定的哪 \(k ...
- BZOJ2820:YY的GCD——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=2820 Description 神犇YY虐完数论后给傻×kAc出了一题给定N, M,求1<=x& ...
- bzoj2330: [SCOI2011]糖果(差分约束)
差分约束裸题,a==b的话分别建a>=b a<=b的边就行.倒序加边不然会TLE是什么鬼 #include<iostream> #include<cstring> ...
- 创建JavaScript的哈希表Hashtable
Hashtable是最常用的数据结构之一,但在JavaScript里没有各种数据结构对象.但是我们可以利用动态语言的一些特性来实现一些常用的数据结构和操作,这样可以使一些复杂的代码逻辑更清晰,也更符合 ...
- mybatis逆向工程生成mapper报错
Result Maps collection already contains value for xxxMapper.BaseResultMap错误解决办法一.问题描述今天在做项目时,遇到一个错误: ...
- POJ2528 线段树离散化
Mayor's posters Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 62771 Accepted: 18120 ...
- JupyterHub的安装与配置——让Jupyter支持多用户
1.下载anaconda 打开https://www.continuum.io/downloads,找到自己要的版本 如:https://repo.anaconda.com/archive/Anaco ...
- Android如何在初始化的时候获取加载的布局的宽高
在自定义ListView中,需要将下拉刷新的View在初始化的时候设置padding隐藏起来,这时就要在初始化的时候获得要加载的布局View的高度. private View headView; he ...
- 2015/9/20 Python基础(16):类和实例
面向对象编程编程的发展已经从简单控制流中按步的指令序列进入到更有组织的方式中,依靠代码块可以形成命名子程序和完成既定的功能.结构化的或过程性编程可以让我们把程序组织成逻辑快,以便重复或重用.创造程序的 ...
- Maven -- 在进行war打包时用正式环境的配置覆盖开发环境的配置
我们的配置文件一般都放在 src/main/resource 目录下. 假定我们的正式环境配置放在 src/main/online-resource 目录下. 那么打成war包时,我们希望用onli ...