您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS SDK 詳解之 NSDictionary 與 NSMutableDictionary

編輯:iOS 開發綜合

NSDictionary 是 Cocoa 中最核心的資料結構之一:以 key-value 的形式儲存資料,查找時間接近常數,語意直觀。本文整理它的核心概念與常用 API,並補上實務上容易忽略的細節。

一、NSDictionary / NSMutableDictionary 概述

NSDictionary 提供 key-value 的儲存方式。要點如下:

· 任何遵循 NSCopying 協議的物件都可以作為 key;
· key 不可重複(以 isEqual: 判斷相等性,並搭配 hash);
· key 與 value 都不能為 nil,若需表達「空值」,請使用 NSNull;
· NSDictionary 的內容不可變,NSMutableDictionary 則是它的可變子類。

二、常用屬性與方法

2.1 建立與初始化

(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];

2.2 count —— 取得 key-value 對數量

NSDictionary *dic = @{@"key1": @"1", @"key2": @"2"};
NSLog(@"%ld", (unsigned long)dic.count);

2.3 isEqualToDictionary: —— 比較內容是否相同

注意它比較的是**內容**而非物件身分,因此 key 的順序不影響結果。

NSDictionary *dic1 = @{@"key1": @"1", @"key2": @"2"};
NSDictionary *dic2 = @{@"key2": @"2", @"key1": @"1"};
if ([dic1 isEqualToDictionary:dic2]) {
    NSLog(@"Equal contents");
}

2.4 objectForKey: 與 valueForKey:

NSLog(@"%@", [dic1 objectForKey:@"key1"]);
NSLog(@"%@", [dic1 valueForKey:@"key2"]);

兩者的差異在於 KVC 支援:valueForKey: 若傳入 @"" 會回傳整個字典,若 key 以 @ 開頭亦有特殊行為;一般取值用 objectForKey: 更安全。

2.5 allKeys 與 allValues

NSArray *keys = [dic1 allKeys];
NSArray *values = [dic1 allValues];

2.6 enumerateKeysAndObjectsUsingBlock: —— 以 Block 遍歷

[dic1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSLog(@"%@ => %@", [key description], [obj description]);
    // 將 *stop 設為 YES 可提早中斷遍歷
}];

2.7 排序

三個排序方法都會回傳「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"
)

2.8 過濾:keysOfEntriesPassingTest:

回傳符合 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
}

2.9 寫入檔案

· 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");
}

2.10 description

debug 時最常用的一招,直接 NSLog(@"%@", dic) 或取 dic.description 即可印出完整內容。

三、NSMutableDictionary 的額外方法

3.1 加入元素

- (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;
}

3.2 刪除元素

- (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 或資料庫會是更好的選擇。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved