NSDictionary的创建
NSDictionary *dict = @{
@"name":@"frank",
@"age":@25,
@"job":@"coder"
}
// dictionaryWithObjectsAndKeys类方法。使用该方法创建字典时,注意其顺序是:value、key并且要以nil结尾。
NSDictionary *dict2 = [NSDictonary dictionaryWithObjectsAndKeys:
@"china",
@"nation",
@"male",
@"sexual",
nil
]
// 使用键数组和值数组创建字典。把字典中的key以及value,按照对应顺序,分别放在一个数组中,然后调用dictionaryWithObjects: forKeys:方法,创建字典。
NSArray *aKeys = @[@"language", @"IDE"];
NSArray *aValues = @[@"objective-c", @"xcode"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObjects: aValues, forKeys:aKeys];
// 访问字典的键值
1、使用dict[key]的形式。
2、objectForKey
NSString job = [dict objectForKey:@"job"];
// for-in循环除了能够用于遍历数组中的对象之外,也可以用于遍历字典中的键值对。
for (NSDictionary *key in dict) {
NSLog(@"key:%@ value:%@", key dict[key]);
}
@property (readonly) NSUinteger count; // 获取字典中键值对的数量
@property (readonly, copy) NSArray<KeyType> *allKeys; // 获取字典中的所有键
@property (readonly, copy) NSArray<ObjectType> *allValues; // 获取字典中的所有值
NSMutableDictionary
创建 初始化
+(instancetype)dictionary;
// dictionaryWithCapacity:方法:使用该方法创建可变字典对象时,需要预先指定可变字典的容量,在初始化时会根据传入的容量参数在内存中预先分配空间。
+(instancetype)dictionaryWithCapacity:(NSUIntege)numItem;
// initWithContentsOfFile:方法:从指定文件初始化得到一个可变字典对象。
-(nullable NSMutableDictionary<KeyType, ObjectType> *)initWithContentsOffFile:(NSString *)path;
// setObject:forKey:方法,可变字典内存储的键值可以增加。
+(void)setObject:(ObjectType)anObject forKey:(KetType<NSCopying>) aKey;
// removeObjectForKey:方法,可以移除某个键值对。
-(void)removeObjectForKey:(KeyType) aKey;
// removeObjectsForKeys:方法,可以移除多个键值对,把需要移除的所有键存储在一个数组对象中,作为参数传入。
-(void)removeOObjectsForKeys:(NSArray<KeyTypw> *)keyArray;
// removeAllObjects;方法,可以移除可变字典中的所有键值对。
-(void)removeAllObjects;