NSMutableDictionary和NSDictionary区别
NSMutableDictionary是一个可以变长的字典NSDictionary是一个不可变长字典
NSDictionary:是继承与NSObject,这里是一个key对应一个value,key是唯一的 不能为nil,但是value是唯一且可以为nil
NSMutableDictionary:是继承与NSDictionary可以理解成用来存取NSDictionary的集合
- NSDictionary用法
1.创建一个NSDictionary一个对象
NSDictionary *mNSDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
@"value4", @"key4",
@"value5", @"key6",
@"value6", @"key6",
nil];
NSDictionary *mNSDictionary1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
可以看出使用dictionaryWithObjectsAndKeys和dictionaryWithObject可以创建一个或者多个点键值对
2.通过key来获取NSDictionary中对应的值
//通过key获取Value
[mNSDictionary objectForKey:@"key5"];
NSLog(@"%@",[mNSDictionary objectForKey:@"key5"]);
3.获取全部key,全部value
//所有的键集合
NSArray *keys = [mNSDictionary allKeys];
NSLog(@"keys :%@", keys);
//所有值集合
NSArray *values = [mNSDictionary allValues];
NSLog(@"values :%@", values);
4.获取键值NSDictionary个数
NSLog(@"values :%ld", [mNSDictionary count]);
- NSMutableDictionary用法
1.创建NSMutableDictionary
NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
@"value4", @"key4",
@"value5", @"key5",
nil];
NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
2.删除键所对应的键值对
[dic1 removeObjectForKey:@"key1"];
//通过键集合删除来删除
NSArray *array = @[@"key1",@"key2",@"key3"];
[dic6 removeObjectsForKeys:array];
3.移除字典中的所有对象
[dic1 removeAllObjects];
- NSDictionary转换为NSMutableDictionary
//初始化可变字典
NSDictionary *mNSDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
@"value4", @"key4",
@"value5", @"key6",
@"value6", @"key6",
nil];
//初始化一个空的可变字典
NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
[dic2 addEntriesFromDictionary:mNSDictionary];
3.遍历
NSDictionary *mNSDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
@"value4", @"key4",
@"value5", @"key6",
@"value6", @"key6",
nil];
//初始化一个空的可变字典
NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
[dic2 addEntriesFromDictionary:mNSDictionary];
for (NSString *key in dic2) {
NSLog(@"%@",[dic2 objectForKey:key]);
}