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

原文地址:https://www.cnblogs.com/smithjackyson/p/5074039.html