NSDictionary 是 Cocoa 中最核心的資料結構之一:以 key-value 的形式儲存資料,查找時間接近常數,語意直觀。本文整理它的核心概念與常用 API,並補上實務上容易忽略的細節。
NSDictionary 提供 key-value 的儲存方式。要點如下:
· 任何遵循 NSCopying 協議的物件都可以作為 key;
· key 不可重複(以 isEqual: 判斷相等性,並搭配 hash);
· key 與 value 都不能為 nil,若需表達「空值」,請使用 NSNull;
· NSDictionary 的內容不可變,NSMutableDictionary 則是它的可變子類。
(instancetype)dictionaryWithContentsOfFile:(NSString *)path; (instancetype)dictionary; (instancetype)dictionaryWithDictionary:(NSDictionary *)dict; (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys; (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
對應的 init 版本:
- (NSDictionary *)init; - (NSDictionary *)initWithContentsOfFile:(NSString *)path; - (NSDictionary *)initWithDictionary:(NSDictionary *)dict; - (NSDictionary *)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys; - (NSDictionary *)initWithObjectsAndKeys:(id)firstObject, ...;
當然,別忘了更簡潔的字面語法 @{}:
NSDictionary *emptyDic = [NSDictionary dictionary];
NSDictionary *firstDic = @{@"key": @"value", @"first": @"1"};
NSDictionary *secondDic = [[NSDictionary alloc] initWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2", nil];
NSDictionary *dic = @{@"key1": @"1", @"key2": @"2"};
NSLog(@"%ld", (unsigned long)dic.count);
注意它比較的是**內容**而非物件身分,因此 key 的順序不影響結果。
NSDictionary *dic1 = @{@"key1": @"1", @"key2": @"2"};
NSDictionary *dic2 = @{@"key2": @"2", @"key1": @"1"};
if ([dic1 isEqualToDictionary:dic2]) {
NSLog(@"Equal contents");
}
NSLog(@"%@", [dic1 objectForKey:@"key1"]); NSLog(@"%@", [dic1 valueForKey:@"key2"]);
兩者的差異在於 KVC 支援:valueForKey: 若傳入 @"" 會回傳整個字典,若 key 以 @ 開頭亦有特殊行為;一般取值用 objectForKey: 更安全。
NSArray *keys = [dic1 allKeys]; NSArray *values = [dic1 allValues];
[dic1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@ => %@", [key description], [obj description]);
// 將 *stop 設為 YES 可提早中斷遍歷
}];
三個排序方法都會回傳「key 的陣列」,順序依 value 的大小決定:
· keysSortedByValueUsingSelector:
· keysSortedByValueUsingComparator:
· keysSortedByValueWithOptions:usingComparator:
NSDictionary *numsDic = @{@(2): @"second", @(1): @"first", @(3): @"thrid"};
NSDictionary *strDic = @{@"id_1": @"first", @"id_3": @"thrid", @"id_2": @"second"};
NSArray *numsSortedKeys = [numsDic keysSortedByValueUsingSelector:@selector(compare:)];
NSArray *strSortedKeys = [strDic keysSortedByValueUsingComparator:
^NSComparisonResult(id obj1, id obj2) {
return [(NSString *)obj1 compare:(NSString *)obj2];
}];
輸出:
(
1,
2,
3
)
(
"id_1",
"id_2",
"id_3"
)
回傳符合 block 條件的 key 集合(NSSet):
NSDictionary *numsDic = @{@(2): @"second", @(1): @"first", @(3): @"thrid"};
NSSet *filteredKeys = [numsDic keysOfEntriesPassingTest:
^BOOL(id key, id obj, BOOL *stop) {
return ((NSNumber *)key).integerValue > 2;
}];
NSLog(@"%@", filteredKeys.description);
輸出:
{
3
}
· writeToFile:atomically:
· writeToURL:atomically:
只有 plist 可序列化的型別(NSString、NSNumber、NSData、NSDate、NSArray、NSDictionary)才能這樣存。
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [path stringByAppendingPathComponent:@"file"];
NSDictionary *dic = @{@"key": @"value"};
if ([dic writeToFile:filePath atomically:YES]) {
NSLog(@"Success");
}
debug 時最常用的一招,直接 NSLog(@"%@", dic) 或取 dic.description 即可印出完整內容。
- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey; - (void)setValue:(id)value forKey:(NSString *)key; - (void)setDictionary:(NSDictionary *)otherDictionary;
使用 KVC 版本的 setValue:forKey: 時,key 必須是 NSString;第三個方法會**先清空**原有內容,再放入 otherDictionary 的元素,不是合併。
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"object", @"key", nil];
NSLog(@"%@", dic.description);
[dic setDictionary:@{@"otherKey": @"otherValue"}];
NSLog(@"%@", dic.description);
輸出:
{
key = object;
}
{
otherKey = otherValue;
}
- (void)removeObjectForKey:(id)aKey; - (void)removeAllObjects; - (void)removeObjectsForKeys:(NSArray *)keyArray;
第三個方法一次移除多個 key,很實用卻常被忽略:
NSDictionary *dic = @{@(1): @"first", @(2): @"second", @(3): @"thrid"};
NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
[mutableDic removeObjectsForKeys:@[@(1), @(2)]];
NSLog(@"%@", mutableDic.description);
輸出:
{
3 = thrid;
}
· NSDictionary 不保證遍歷順序,若需要有序請改用 NSArray 搭配 NSNumber 索引,或自行排序。
· 用自訂類別當 key 時,務必同時正確實作 hash 與 isEqual:,兩者必須一致。
· 從 plist 讀回的資料顆粒較粗,若資料量大或需局部更新,Core Data 或資料庫會是更好的選擇。