NSDictionary用于保存具有映射关系的数据,因此NSDictionary集合里保存着两组值,一组值用于保存NSDictionary里的key,另一组用于保存NSDictionary里的value。注意,key和value都可以是任何指针类型的数据,NSDictionary的key不允许重复。
key和value之间存在单向一对一关系,即通过指定的key,总能找到唯一的、确定的value。从NSDictionary中取出数据时,只要给出指定的key,总能找到唯一的、确定的value。从NSDictionary中取出数据时,只要给出指定的key,就可以取出对应的value。
NSDictionary的功能与用法
NSDictionary分别提供了类方法和实例方法来创建NSDictionary,类方法以dictionary开头,实例方法则以init开头:
- dictionary创建一个不包含任何key-value对的NSDictionary。
- dictionaryWithContentsOfFile:/initWithContentsOfFile:读取指定文件的内容,使- 用指定的文件内容来初始化NSDictionary。该文件通常是由NSDictionary输出生成的。
- dictionaryWithDictionary:/initWithDictionary:使用已有的NSDictionary包含的key-value对来初始化NSDictionary对象。
- dictionaryWithObject:forKey:使用单个key-value对来创建NSDictionary对像。
dictionaryWithObjects:forKeys:/initWithObjects:forKeys:使用两个NSArray分别指定key、value集合,可以创建包含多个key-value对的NSDictionary。 - dictionaryWithObjectsAndKeys:/initWithObjectsAndKeys:调用该方法时,需要按value1,key1,value2,key2,…,nil的格式传入多个key-value对。
除此之外,还可以使用如下简化语法来创建NSDictionary对象:
@{
key1: value1, key2: value2...}
示例:
//NSDictionary+print.h
@interface NSDictionary(print)
- (void) print;
@end
//NSDictionary+print.m
#import "NSDictionary+print.h"
@implementation NSDictionary (print)
- (void) print
{
NSMutableString* result = [NSMutableString stringWithString:@"{"];
//使用快速枚举语法来遍历NSDictionary
//循环计数器将依次等于该NSDictionary的每个key
for (id key in self) {
[result appendString:[key description]];
[result appendString:@"="];
//使用下标法根据key来获取对应的value
[result appendString:[self [key] description]];
[result appendString:@", "];
}
//获取字符串长度
NSUInteger len = [result length];
//去掉字符串最后两个字符
[result deleteCharactersInRange:NSMakeRange(len - 2, 2)];
[result appendString:@"}"];
NSLog(@"%@" , result);
}
@end
#import <Foundation/Foundation.h>
#import "NSDictionary+print.h"
#import "FKUser.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//直接使用多个value-key对的形式创建NSDictionary对象
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
[[FKUser alloc] initWithName:@"sun"] , @"one",
[[FKUser alloc] initWithName:@"bai"] , @"two",
[[FKUser alloc] initWithName:@"sun"] , @"three",
[[FKUser alloc] initWithName:@"Tang"] , @"four",
[[FKUser alloc] initWithName:@"niu"] , @"five" ,nil];
[dict print];
NSLog(@"dict包含%ld个key-value对" , [dict count]);
NSLog(@"dict的所有key为:%@" , [dict allKeys]);
NSLog(@"<FKUser[name = sun]>对应的所有key为:%@" , [dict allKeysForObject:[[FKUser alloc] initWithName:@"sun"]]);
//获取遍历dict所有value的枚举器
NSEnumerator* en = [dict objectEnumerator];
id value;
//使用枚举器来遍历dict中所有的value
while (value = [en nextObject]) {
NSLog(@"%@" , value);
}
//使用指定代码块来迭代执行该集合中所有的key-value对
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop)
{
NSLog(@"key的值为:%@" , key);
[value say:@"疯狂iOS讲义"];
}];
}
return 0;
}
效果:
对NSDictionary的key排序
NSDictionary还提供了方法对NSDictionary的所有key执行排序,这些方法执行完成后将返回排序好的所有key组成的NSArray。
- keysSortedByValueUsingSelector::根据所有value指定方法的返回值对key排序;调用该方法必须返回NSOrderedAscending、NSOrderedDescending、NSOrderedSame这三个枚举值之一。
- keysSortedByValueUsingComparator::使用指定的代码块来遍历key-value对,并根据执行结果(必须返回NSOrderedAscending、NSOrderedDescending、NSOrderedSame这三个枚举值之一)对所有key进行排序。
- keysSortedByValueWithOptions:usingComparator::与前一个方法的功能类似,只是可以传入一个额外的NSEnumerationOptions参数。
示例:
//main.m
#import <Foundation/Foundation.h>
#import "NSDictionary+print.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//使用简化语法创建NSDictionary对象
NSDictionary* dict = @{
@"one":@"Objective-C",
@"two":@"Ruby",
@"three":@"Python",
@"four":@"Perl"
};
//打印dict集合的所有元素
[dict print];
//获取所有直接调用value的compare:方法对所有的key进行排序
//返回排序好的所有key组成的NSArray
NSArray* keyArr1 = [dict keysSortedByValueUsingSelector:@selector(compare:)];
NSLog(@"%@" , keyArr1);
NSArray* keyArr2 = [dict keysSortedByValueUsingComparator:^(id value1, id value2)
{
//下面定义比较大小的标准:字符串越长,即可认为value越大
if([value1 length] > [value2 length]) {
return NSOrderedDescending;
}
if([value1 length] < [value2 length]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
NSLog(@"%@" , keyArr2);
//将NSDictionary的内容输出到指定文件中
[dict writeToFile:@"myfile.txt" atomically:YES];
}
return 0;
}
效果:
对NSDictionary的key进行过滤
NSDictionary还提供了方法对NSDictionary的所有key执行过滤,这些方法执行完将返回满足条件的key组成的NSSet。方法如下:
- keysOfEntriesPassingTest::使用代码块迭代处理NSDictionary的每个key-value对。对NSDictionary的key-value对进行过滤,该代码块必须返回BOOL类型的值,只有当该代码块返回YES时,该key才会被保留下来;该代码块可以接受3个参数,其中第一个参数代表正在迭代处理的key,第二个参数代表正在迭代处理的value,第三个参数代表是否还要继续迭代,如果将第三个参数设为NO,那么该迭代会立即停止。
- keysOfEntriesWithOptions:passingTest::该方法的功能与前一个方法的功能基本相同。只是该方法可以额外传入一个附加的NSEnumerationOptions选项参数。
示例:
#import <Foundation/Foundation.h>
#import "NSDictionary+print.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDictionary* dict = @{
@"Objective-C":[NSNumber numberWithInt:89],
@"Ruby":[NSNumber numberWithInt:69],
@"Python":[NSNumber numberWithInt:75],
@"Perl":[NSNumber numberWithInt:109],
};
[dict print];
NSSet* keySet = [dict keysOfEntriesPassingTest:^(id key, id value, BOOL* stop) {
return (BOOL)([value intValue] > 80);
}];
NSLog(@"%@" , keySet);
}
return 0;
}
效果:
使用自定义类作为NSDictionary的key
如果程序打算使用自定义类作为NSDictionary的key,则该自定义类必须满足如下需求:
该自定义类正确重写过isEqual: 和hash方法。所谓正确重写,是指当两个对象通过isEqual:方法判断相等时,两个对象的hash方法返回值也相等。
该自定义类必须实现了copyWithZone:方法,该方法最好返回该对象的不可变副本。
为什么要实现copyWithZone:方法呢?因为对于NSDictionary来说,key是非常关键的,NSDictionary需要根据key来访问value——从这个意义上看,key相当于NSDictionary的索引,如果key本身是可变的,且程序可以通过其他变量来修改NSDictionary的key,这就可能导致NSDictionary的“索引”值被破坏,从而导致NSDictionary的完整性被破坏。
为了让前面的User类作为NSDictionary的key,还需要让该User类实现NSCopying协议(可选的,通常建议实现),并让该User类实现copyWithZone:方法。User实现的copyWithZone:方法如下:
-(id) copyWithZone: (NSZone*) zone {
NSLog(@"--正在复制--");
//复制一个对象
User* newUser = [[[self class] allocWithZone:zone] init];
//将被复制的对象的实例变量的值赋给新对象的实例变量
newUser->_name = _name;
newUser->_pass = _pass;
return newUser;
}
NSMutableDictionary的功能与用法
NSMutableDictionary继承了NSDictionary,它代表一个key-value对可变的NSDictionary集合。由于NSMutableDictionary可以动态地添加key-value对,因此,创建NSMutableDictionary集合时可以指定初始容量。
NSMutableDictionary主要新增了如下方法:
- setObject:forKey::设置一个key-value对。如果NSDictionary中没有包含与该key相同的key-value对,那么NSDictionary将会新增一个key-value对;否则该key-value对将覆盖已有的key-value对。
- setObject:forKeyedSubscript::通过该方法的支持,允许程序通过下标法来设置key-value对。
- addEntriesFromDictionary::将另一个NSDictionary中所有的key-value对复制到当前NSDictionary中。
- setDictionary::用另一个NSDictionary中所有的key-value对替换当前NSDictionary中的key-value对。
- removeObjectForKey::根据key来删除key-value对。
- removeAllObjects:清空该NSDictionary。
- removeObjectsForKeys::使用多个key组成的NSArray作为参数,同时删除多个key对应的key-value对。
示例:
#import <Foundation/Foundation.h>
#import "NSDictionary+print.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//使用单个key-value对来创建NSMutableDictionary对象
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:89], @"疯狂iOS讲义", nil];
//使用下标法设置key-value对,由于NSDictionary中已存在该key
//因此此处设置的value会覆盖前面的value
dict[@"疯狂Android讲义"] = [NSNumber numberWithInt:99];
[dict print];
NSLog(@"--再次添加key-value对--");
dict[@"疯狂XML讲义"] = [NSNumber numberWithInt:69];
[dict print];
NSDictionary* dict2 = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:79], @"疯狂Ajax讲义",
[NSNumber numberWithInt:79], @"疯狂Swift讲义",nil];
//将另一个NSDictionary中的key-value对添加到当前NSDictionary中
[dict addEntriesFromDictionary:dict2];
[dict print];
//根据key来删除key-value
[dict removeObjectForKey:@"疯狂Swift讲义"];
[dict print];
}
return 0;
}
效果: