目录:
1、NSDictionary
2、NSMutableDictionary
1、NSDictionary
//NSDictionary的创建(NSDictionary的初始化)
//方式1
//键值对 :一个键对应一个值
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"aaaa",@"a",@"bbbb",@"b",@"cccc",@"c",@"dddd",@"d",nil];
NSArray *arr = @[@1,@2,@3];
NSArray *arr1 = @[@"a",@"b",@"c"];
NSDictionary *dic =[NSDictionary dictionaryWithObjects:arr forKeys:arr1];
//方式2 通过其它字典创建新的字典
NSDictionary * dic2 = [NSDictionary dictionaryWithDictionary:dic];
NSLog(@"%@",dic2);
//方式3 (常用 重要)
//NSArray * arr = @[@2,@"11",3.14];//不能放C语言的数据类型
//字典也不能放C语言的数据类型 它的键key 通常为字符串 所以咱们写的时候 把字典的键也都设为字符串
NSDictionary * dic3 = @{@"key":@"value",@"name":@"凹凸曼",@"sex":@"man"};
NSLog(@"%@",dic3);
NSLog(@"%@",[dic3 objectForKey:@"sex"]);
NSDictionary *dic = @{@"name":@"王大锤",@"age":@18,@"hobby":@"拍电影"};
NSLog(@"%@",dic);
NSLog(@"%@",dic.allKeys); //allkeys,为一个属性名,获得为一个数组,数组包含所有的key
NSLog(@"%@",[dic objectForKey:@"name"]);
NSDictionary *dic = @{@"name":@"王大锤",@"age":@18,@"hobby":@"拍电影"};
NSLog(@"%@",dic);
for (NSString * key in [dic allKeys])
{
NSLog(@"%@",key);
NSLog(@"%@",[dic objectForKey:key);
}
2、NSMutableDictionary(是NSDictionary的子类,父类方法均可用)
//NSMutableDictionary使用之前必须初始化
self.mtbDict = [NSMutableDictionary dictionary];
//使用字典初始化:可以是可变字典,也可以是不可变字典
self.mtbDict = [NSMutableDictionary dictionaryWithDictionary:@{}];
//可变字典可以增加、删除、覆盖。。。
//常用方法
- (void)removeObjectForKey:(KeyType)aKey;
- (void)setObject:(ObjectType)anObject forKey:(KeyType <NSCopying>)aKey;
- (void)addEntriesFromDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary;
- (void)removeAllObjects;
- (void)removeObjectsForKeys:(NSArray<KeyType> *)keyArray;
+ (nullable NSMutableDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfFile:(NSString *)path;
+ (nullable NSMutableDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfURL:(NSURL *)url;
- (nullable NSMutableDictionary<KeyType, ObjectType> *)initWithContentsOfFile:(NSString *)path;
- (nullable NSMutableDictionary<KeyType, ObjectType> *)initWithContentsOfURL:(NSURL *)url;