同数组(NSArray),字典类NSDictionary也支持字面量语法糖(Object Literals Syntactic Sugar),允许我们方便地基于字面量定义初始化字典对象。以下基于字面量语法快捷初始化字典(NSDictionary):
NSDictionary* literalDictionary = @{@"k1":@"v1", @"k2":@"v2", @"k3":@"v3"};
需要注意的是数组是有序的,按照addObject的顺序存放;字典是无序的,在进行枚举时,读取的键-值顺序不一定和写入的顺序一致。
- (instancetype)init NS_DESIGNATED_INITIALIZER;
// 基于va_list初始化NSDictionary
- (instancetype)initWithObjectsAndKeys:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
// 基于keys数组和对应的values数组初始化NSDictionary
- (instancetype)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
// 基于other Dictionary初始化新的NSDictionary
- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary;
- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag;
+ (instancetype)dictionary;
// 以一对key-value初始化NSDictionary
+ (instancetype)dictionaryWithObject:(id)object forKey:(id )key;
// initWithObjectsAndKeys:对应的类静态实例化方法
+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
// initWithObjects:forKeys:对应的类静态实例化方法
+ (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
// initWithDictionary:对应的类静态实例化方法
+ (instancetype)dictionaryWithDictionary:(NSDictionary *)dict;
以下是简单的示例:
NSDictionary* queryItemDict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"v1", @"k1", @"v2", @"k2", @"v3", @"k3", nil];
NSLog(@"queryItemDict1 = %@", queryItemDict1);
NSDictionary* queryItemDict2 = [NSDictionary dictionaryWithObjects:@[@"v1", @"v2", @"v3"] forKeys:@[@"k1", @"k2", @"k3"]];
NSLog(@"queryItemDict2 = %@", queryItemDict2);
@property (readonly) NSUInteger count;
可以基于dictionary.count对字典进行判空:如果dictionary.count=0,则表示字典为nil或不包含任何键值对。
@property (readonly, copy) NSArray *allKeys; // 所有key的数组
@property (readonly, copy) NSArray *allValues; // 所有value的数组
// 查找key对应的value(NSObject)
- (id)objectForKey:(id)aKey;
// 等效于objectForKey,支持中括号下标格式(dictionary[key])访问指定键的值。
- (id)objectForKeyedSubscript:(id)key NS_AVAILABLE(10_8, 6_0);
// 查找value相同的所有keys
- (NSArray *)allKeysForObject:(id)anObject;
// 基于keys数组查找对应的values数组
- (NSArray *)objectsForKeys:(NSArray *)keys notFoundMarker:(id)marker;
以下objectsForKeys:notFoundMarker:示例:
NSArray *keyArr = @[@"k1", @"k2", @"k3"];
NSArray *objArr = [NSArray arrayWithObjects:@"v1", @"v2", @"v3", nil];
NSArray *srcArr = [NSArray arrayWithObjects:@"k0", @"k2", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objArr forKeys:keyArr];
// NSArray *resArr = [dict objectsForKeys:srcArr notFoundMarker:@"not found"]; // ("not found", v2)
NSArray *resArr = [dict objectsForKeys:srcArr notFoundMarker:[NSNull null]]; // ("", v2)
- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
- (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate NS_AVAILABLE(10_6, 4_0);
keysSortedByValueUsingSelector/keysSortedByValueUsingComparator通过使用指定SEL或NSComarator来对allKeys进行排序,然后通过objectsForKeys取出排序后的键-值对。
- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator;
- (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr NS_AVAILABLE(10_6, 4_0);
除了继承NSDictionary基本的init,还增加了以下指定初始化函数:
- (instancetype)initWithCapacity:(NSUInteger)numItems NS_DESIGNATED_INITIALIZER;
// 赋值替换键值对
- (void)setObject:(id)anObject forKey:(id )aKey;
// 等效于setObject:forKey:,支持中括号下标格式(dictionary[key]=)赋值替换。
- (void)setObject:(id)obj forKeyedSubscript:(id )key NS_AVAILABLE(10_8, 6_0);
例如,以下代码片段获取URL Components查询串中的queryItem Dictionary:
// http://weixin.sogou.com/weixin?type=2&ie=utf-8&query=NASA发现新地球
NSString* wxNASAURLPath = @"http://weixin.sogou.com/weixin?type=2&ie=utf-8&query=NASA%E5%8F%91%E7%8E%B0%E6%96%B0%E5%9C%B0%E7%90%83";
NSURLComponents* wxNASAURLComponents = [NSURLComponents componentsWithString:wxNASAURLPath];
NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary];
NSArray* queryItems = wxNASAURLComponents.queryItems;
for (NSURLQueryItem* item in queryItems) {
[queryItemDict setObject:item.value forKey:item.name];
}
NSLog(@"queryItemDict = %@", queryItemDict);
// 从otherDictionary追加entries到当前Dictionary
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;
// 等效于先removeAllObjects后addObjectsFromArray;setDictionary类似于对retain propery的赋值(setter)。
- (void)setDictionary:(NSDictionary *)otherDictionary;
// 删除指定key的键值对
- (void)removeObjectForKey:(id)aKey;
// 删除指定key数组对应的键值对
- (void)removeObjectsForKeys:(NSArray *)keyArray;
// 删除清空所有键值对
- (void)removeAllObjects;
《NSDictionary API学习》《OC字典NSDictionary》
《OC基础集合类》《Objective-C研究院之词典对象(八)》
《NSDictionary/NSMutableDictionary 及 NSArray/NSmutableArray (实例)》