NSDictionary基本用法
//创建
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSLog(@"%@",dic[@"key"]);
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key",@"A",@"a",@"B",@"b",@"C",@"c", nil];
NSLog(@"%@",dic1[@"key"]);
NSDictionary *dic2 = @{@"key":@"value",@"a":@"A",@"b":@"B",@"c":@"C"};
NSLog(@"%@",dic2[@"key"]);
键值对个数
NSLog(@"%lu",(unsigned long)[dic1 count]);//4
NSArray *keys = [dic1 allKeys];
NSLog(@"%@",keys);//b,key,c,a
NSArray *values = [dic1 allValues];
NSLog(@"%@",values);//B,value,C,A
遍历
[dic2 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"key:%@--obj:%@",key,obj);
}];
/*
key:b--obj:B
key:key--obj:value
key:c--obj:C
key:a--obj:A
*/
字典读写(无序)
BOOL flag = [dic2 writeToFile:@"/Users/soso/Desktop/demo1/NSArray/demo.plist" atomically:YES];
NSLog(@"%d",flag);
NSDictionary *dic3 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/soso/Desktop/demo1/NSArray/demo.plist"];
NSLog(@"%@",dic3);
/*
a = A;
b = B;
c = C;
key = value;
*/
NSMutableDictionary
//创建一个空字典
NSMutableDictionary *dic4 = [NSMutableDictionary dictionary];
//添加
[dic4 setObject:@"value" forKey:@"key"];
//将传入字典所有的键值对取出来添加到dic中
[dic4 setValuesForKeysWithDictionary:@{@"key1":@"Value1"}];
NSLog(@"%@",dic4);
/*
key = value;
key1 = Value1;
*/
//删除
[dic4 removeObjectForKey:@"key1"];
NSLog(@"%@",dic4);//key = value;
[dic4 removeObjectsForKeys:@[@"key",@"key1"]];
NSLog(@"%@",dic4);
[dic4 removeAllObjects];
//修改
[dic4 setObject:@"newValue" forKey:@"key"];
NSLog(@"%@",dic4);
/*
key = newValue;
key1 = Value1;
*/
网友评论