本文把 NSDictionary 與 NSMutableDictionary 的介面依功能重組,並為容易搞錯的排序與過濾方法補上可運行的範例與實際輸出。
@property (readonly) NSUInteger count; // 鍵值對數量
- (id)objectForKey:(id)aKey; // 以 key 取 value
- (NSEnumerator *)keyEnumerator; // 遍歷所有 key
- (instancetype)init NS_DESIGNATED_INITIALIZER;
#if TARGET_OS_WIN32
- (instancetype)initWithObjects:(const id [])objects forKeys:(const id [])keys
count:(NSUInteger)cnt;
#else
- (instancetype)initWithObjects:(const id [])objects
forKeys:(const id <NSCopying> [])keys
count:(NSUInteger)cnt NS_DESIGNATED_INITIALIZER;
#endif
@property (readonly, copy) NSArray *allKeys; // 所有 key
- (NSArray *)allKeysForObject:(id)anObject; // 由 value 反查所有對應的 key
@property (readonly, copy) NSArray *allValues; // 所有 value
- (NSEnumerator *)objectEnumerator; // 遍歷所有 value
- (NSArray *)objectsForKeys:(NSArray *)keys
notFoundMarker:(id)marker; // 批量取值,找不到時用 marker 代替
- (id)objectForKeyedSubscript:(id)key NS_AVAILABLE(10_8, 6_0); // 支援 dict[key] 寫法
- (void)getObjects:(id __unsafe_unretained [])objects
andKeys:(id __unsafe_unretained [])keys;
notFoundMarker 的實際行為:
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
@"K1", @"V1", @"K2", @"V2", @"K3", @"V3", nil];
NSArray *arr1 = [NSArray arrayWithObjects:@"V1", @"V2", @"VG", nil];
NSArray *result = [dic objectsForKeys:arr1 notFoundMarker:@"BB"];
NSLog(@"結果:%@", result);
// 輸出:( K1, BB, BB )
@property (readonly, copy) NSString *description; @property (readonly, copy) NSString *descriptionInStringsFileFormat; - (NSString *)descriptionWithLocale:(id)locale; - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level; - (BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary;
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically; // 若 URL 型別不支援原子寫入,atomically 參數會被忽略
前提條件是字典中所有 key 與 value 都屬於 plist 支援的型別(NSString、NSNumber、NSData、NSDate、NSArray、NSDictionary)。
這組方法名容易誤解,實際語意是「依 value 的比較結果排序,回傳 key 的陣列」。
// 1. 以 selector 比較
- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator;
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:
@"4", @"A", @"6", @"C", @"5", @"B", nil];
NSArray *arr2 = [dic1 keysSortedByValueUsingSelector:@selector(compare:)];
NSLog(@"結果:%@", arr2);
// 輸出:( A, B, C )
// 2. 以 block 比較,可自訂任意邏輯
- (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr
NS_AVAILABLE(10_6, 4_0);
NSArray *sortedKeys = [dic keysSortedByValueUsingComparator:
^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) return NSOrderedAscending;
if ([obj1 integerValue] < [obj2 integerValue]) return NSOrderedDescending;
return NSOrderedSame;
}];
NSLog(@"排序結果:%@", sortedKeys);
// 輸出:( one, three, two )
// 3. block 比較 + 排序選項
- (NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts
usingComparator:(NSComparator)cmptr
NS_AVAILABLE(10_6, 4_0);
注意回傳順序:上面以數字 1、2、3 為 value 的例子,輸出是 one、three、two,因為 comparator 回傳 NSOrderedAscending 表示 obj1 排在後面。
// 基本列舉,可透過 stop 提前結束
- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
NS_AVAILABLE(10_6, 4_0);
// 加上正序/反序選項
- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(id key, id obj, BOOL *stop))block
NS_AVAILABLE(10_6, 4_0);
block 內能存取外部變數的規則值得留意:__block 修飾的區域變數可寫入,物件型別變數可直接取用,屬性則透過 self 存取。
NSDictionary *dic = [NSDictionary dictionaryWithObjects:
@[@"1", @"2", @"3"] forKeys:@[@"one", @"two", @"three"]];
NSString *stopKey = @"two";
__block BOOL stopEarly = NO;
[dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@,%@", key, obj);
if ([key isEqualToString:stopKey]) {
*stop = YES; // 提前終止列舉
stopEarly = YES; // 寫入 __block 變數
}
}];
// 輸出:
// one,1
// two,2
keysOfEntriesPassingTest: 是很實用的過濾方法,block 回傳 YES 的項目其 key 會被收集成 NSSet 回傳。
- (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate
NS_AVAILABLE(10_6, 4_0);
- (NSSet *)keysOfEntriesWithOptions:(NSEnumerationOptions)opts
passingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate
NS_AVAILABLE(10_6, 4_0);
NSDictionary *numsDic = @{@(2): @"second", @(4): @"first", @(1): @"thrid"};
NSSet *filteredKeys = [numsDic keysOfEntriesPassingTest:
^BOOL(id key, id obj, BOOL *stop) {
return ([key integerValue] > 2);
}];
NSLog(@"結果:%@", filteredKeys);
// 輸出:{ ( 4 ) }
@interface NSDictionary (NSDictionaryCreation)
+ (instancetype)dictionary;
+ (instancetype)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key;
+ (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys
count:(NSUInteger)cnt;
+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
+ (instancetype)dictionaryWithDictionary:(NSDictionary *)dict;
+ (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
+ (NSDictionary *)dictionaryWithContentsOfFile:(NSString *)path;
+ (NSDictionary *)dictionaryWithContentsOfURL:(NSURL *)url;
- (instancetype)initWithObjectsAndKeys:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary;
- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag;
- (instancetype)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
- (NSDictionary *)initWithContentsOfFile:(NSString *)path;
- (NSDictionary *)initWithContentsOfURL:(NSURL *)url;
@end
另外還有現代語法糖: @{@"key": @"value"} 與 dict[@"key"],日常開發應優先使用。
@interface NSMutableDictionary : NSDictionary - (void)removeObjectForKey:(id)aKey; - (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey; - (instancetype)init NS_DESIGNATED_INITIALIZER; - (instancetype)initWithCapacity:(NSUInteger)numItems NS_DESIGNATED_INITIALIZER; @end @interface NSMutableDictionary (NSExtendedMutableDictionary) - (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary; // 合併另一字典 - (void)removeAllObjects; - (void)removeObjectsForKeys:(NSArray *)keyArray; - (void)setDictionary:(NSDictionary *)otherDictionary; - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key NS_AVAILABLE(10_8, 6_0); @end @interface NSMutableDictionary (NSMutableDictionaryCreation) + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; + (NSMutableDictionary *)dictionaryWithContentsOfFile:(NSString *)path; + (NSMutableDictionary *)dictionaryWithContentsOfURL:(NSURL *)url; - (NSMutableDictionary *)initWithContentsOfFile:(NSString *)path; - (NSMutableDictionary *)initWithContentsOfURL:(NSURL *)url; @end
@interface NSDictionary (NSSharedKeySetDictionary) // 預先建立鍵集,後續字典可複用,省去重複 copy 的開銷 + (id)sharedKeySetForKeys:(NSArray *)keys NS_AVAILABLE(10_8, 6_0); @end @interface NSMutableDictionary (NSSharedKeySetDictionary) + (NSMutableDictionary *)dictionaryWithSharedKeySet:(id)keyset NS_AVAILABLE(10_8, 6_0); @end
當你要建立成千上萬個結構相同、只有值不同的字典(例如大量模型物件轉字典),使用共享鍵集能顯著降低記憶體佔用。
最後提醒一個實務陷阱:NSDictionary 複製淺層內容,key 會被呼叫 copy,因此自訂類別作為 key 時必須正確實作 copyWithZone: 與 hash/isEqual:,否則查詢會出現無法命中或崩潰。