作者:弦苦 授權本站轉載。
同數組(NSArray),字典類NSDictionary也支持Object Literals,允許我們方便地基於字面量定義初始化字典對象。以下基於字面量語法快捷初始化字典(NSDictionary):
NSDictionary* literalDictionary = @{@"k1":@"v1", @"k2":@"v2", @"k3":@"v3"};
需要注意的是數組是有序的,按照addObject的順序存放;字典是無序的,
1.創建初始化(Initialization&Creation)
1.1 Initializing an Dictionary(NS_DESIGNATED_INITIALIZER)
- (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;
1.2 Creating an Dictionary (autorelease)
+ (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 nil]; NSLog(@"queryItemDict1 = %@", queryItemDict1); NSDictionary* queryItemDict2 = [NSDictionary dictionaryWithObjects:@[@"v1", @"v2", @"v3"] forKeys:@[@"k1", @"k2", @"k3"]]; NSLog(@"queryItemDict2 = %@", queryItemDict2);
2.訪問字典(Querying)
2.1 字典鍵值對個數
@property (readonly) NSUInteger count;
可以基於dictionary.count對字典進行判空:如果dictionary.count=0,則表示字典為nil或不包含任何鍵值對。
@property (readonly, copy) NSArray *allKeys; // 所有key的數組 @property (readonly, copy) NSArray *allValues; // 所有value的數組
2.2 鍵值索引查詢
// 查找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 nil]; NSArray *srcArr = [NSArray arrayWithObjects:@"k0", @"k2", nil 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)
3.遍歷字典(Enumerate)
- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOLBOOL *stop))block NS_AVAILABLE(10_6, 4_0); - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOLBOOL *stop))predicate NS_AVAILABLE(10_6, 4_0);
4.字典排序(Sorting)
keysSortedByValueUsingSelector/keysSortedByValueUsingComparator通過使用指定SEL或NSComarator來對allKeys進行排序。
- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator; - (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr NS_AVAILABLE(10_6, 4_0);
5.可變字典(NSMutableDictionary)
5.1 Initializing an Dictionary(NS_DESIGNATED_INITIALIZER)
除了繼承NSDictionary基本的init,還增加了以下指定初始化函數:
- (instancetype)initWithCapacity:(NSUInteger)numItems NS_DESIGNATED_INITIALIZER;
例如,以下代碼片段獲取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);
5.2 setObject for key
// 賦值替換鍵值對 - (void)setObject:(id)anObject forKey:(id )aKey; // 等效於setObject:forKey:,支持中括號下標格式(dictionary[key]=)賦值替換。 - (void)setObject:(id)obj forKeyedSubscript:(id )key NS_AVAILABLE(10_8, 6_0);
5.3 addEntries & setDictionary
// 從otherDictionary追加entries到當前Dictionary - (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary; // 等效於先removeAllObjects後addObjectsFromArray;setDictionary類似於對retain propery的賦值(setter)。 - (void)setDictionary:(NSDictionary *)otherDictionary;
5.4 removeObject
// 刪除指定key的鍵值對 - (void)removeObjectForKey:(id)aKey; // 刪除指定key數組對應的鍵值對 - (void)removeObjectsForKeys:(NSArray *)keyArray; // 刪除清空所有鍵值對 - (void)removeAllObjects;
6.參考
《NSDictionary API學習》
《OC字典NSDictionary》
《Objective-C研究院之詞典對象(八)》
《NSDictionary/NSMutableDictionary 及 NSArray/NSmutableArray (實例)》
版權聲明:本文為博主原創文章,未經博主允許不得轉載。