Objective-C 集合之NSDictionary的常用方法


OC中NSDictionary是用來存儲鍵值對的字典,字典有兩個特性:

1.無序性,字典中的元素沒有順序,存取元素必須依靠key值找到相應的元素;

2.字典中不存在相同的key值,即key值具有唯一性,但是存在不相同的key值關聯相同的元素

 

屬性

@property(readonlyNSUInteger count

得到字典中元素的個數

@property(readonlycopyNSArrayKeyType *allKeys

返回由字典的key值組成的數組

@property(readonlycopyNSArrayObjectType *allValues

返回由字典的value值組成的數組

 

初始化方法

+ (instancetype)dictionary

創建空字典

+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject...

根據參數列表創建字典,順序是value -- key,即第一個參數為value,第二個參數為key,第三個參數為value,第四個參數為key,依次類推

+ (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects
                                             forKeys:(NSArray<id<NSCopying>> *)keys

根據objects數組和keys數組創建字典

不同方式的初始化

初始化方法:

NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"李世民",@"唐朝",@"劉邦",@"漢朝",@"秦始皇",@"秦朝", nil];

便利構造器:

NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"李世民",@"唐朝",@"劉邦",@"漢朝",@"秦始皇",@"秦朝", nil];

字面量:

NSDictionary *dic2 = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3"};

使用快速枚舉for (NSString *key in dictionary)得到的是字典的key值,要通過key值得到存儲的對象

 

常用方法

- (ObjectType)objectForKey:(KeyType)aKey

根據給出的key值得到value值

- (BOOL)isEqualToDictionary:(NSDictionary<KeyType,ObjectType> *)otherDictionary

判斷兩個字典是否相等

- (NSArray<KeyType> *)allKeysForObject:(ObjectType)anObject

找出所有值為anObject的key,並組成一個數組返回

- (NSEnumerator *)keyEnumerator

得到由字典的key值組成的枚舉器

- (NSEnumerator<ObjectType> *)objectEnumerator

得到由字典的value值組成的枚舉器

- (NSArray<KeyType> *)keysSortedByValueUsingSelector:(SEL)comparator

使用comparator比較器比較字典中的value值,並返回排序后的相應key值的數組

 

可變字典NSMutableDictionary

- (void)setObject:(ObjectType)anObject
               forKey:(id<NSCopying>)aKey

添加key值為aKey,value值為anObject的數據

- (void)removeObjectForKey:(KeyType)aKey

移除key值為aKey的數據

- (void)removeObjectsForKeys:(NSArray<KeyType> *)keyArray

移除由keyArray的元素指定的key的所有數據

- (void)removeAllObjects

移除所有的數據

- (void)addEntriesFromDictionary:(NSDictionary<KeyType,ObjectType> *)otherDictionary

添加字典otherDictionary

- (void)setDictionary:(NSDictionary<KeyType,ObjectType> *)otherDictionary

設置字典內容為otherDictionary

 

 


轉載請注明:作者SmithJackyson


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM