操纵字典内容(NSMutableDictionary)
问题
你希望字典内容能够更具动态性,这样用户或你就可以在字典中添加、删除和插入对象了。然而,NSDictionary 是不可变类,因此一旦创建NSDictionary 对象,你就无法再修改其中的内容。解决方案
如果知道字典会动态变化,那么请使用NSMutableDictionary。NSMutableDictionary 是NSDictionary 的子类,这意味着可以像使用NSDictionary 那样使用NSMutableDictionary。但NSMutableDictionary 提供了额外的一些方法,可以在字典中添加、删除和插入对象。
说明
首先需要实例化NSMutableDictionary 类,可以通过任何构造函数做到这一点。要想创建新的、空的NSMutableDictionary 对象,只需要使用alloc 与init 即可:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
要想向字典中添加对象,需要向字典发送setObject:forKey:消息,同时带上要添加的对
象以及与对象关联的键:
[dictionary setObject:@"Hello World"
forKey:@"english"];
[dictionary setObject:@"Bonjour tout le monde"
forKey:@"french"];
[dictionary setObject:@"Hola Mundo
forKey:@"spanish"];
在使用setObject:forKey:时,你向字典中添加的对象一定是由你提供的键索引的。
要想从字典中删除对象,就必须拥有与对象匹配的键。如果拥有键,那么可以通过
removeObjectForKey:方法删除对象:
[dictionary removeObjectForKey:@"french"];
最后,可以通过removeAllObjects:方法一次性删除字典中的全部对象。参见程序清单。
代码
程序清单 main.m
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:@"Hello World"
forKey:@"english"];
[dictionary setObject:@"Bonjour tout le monde"
forKey:@"french"];
[dictionary setObject:@"Hola Mundo"
forKey:@"spanish"];
NSLog(@"OBJECTS ADDED TO DICTIONARY: %@", dictionary);
[dictionary removeObjectForKey:@"french"];
NSLog(@"OBJECT REMOVED FROM DICTIONARY: %@", dictionary);
[dictionary removeAllObjects];
NSLog(@"ALL OBJECTS REMOVED FROM DICTIONARY: %@", dictionary);
}
return 0;
}
使用
要想使用上述代码,请从Xcode 构建并运行Mac 应用。通过日志控制台,可以查看在应用每个操作后字典都发生了哪些变化:
OBJECTS ADDED TO DICTIONARY: {
english = "Hello World";
french = "Bonjour tout le monde";
spanish = "Hola Mundo";
}
OBJECT REMOVED FROM DICTIONARY: {
english = "Hello World";
spanish = "Hola Mundo";
}
ALL OBJECTS REMOVED FROM DICTIONARY: {
}