NSDictionary基本用法
//創(chuàng)建
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"]);
鍵值對個數(shù)
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
//創(chuàng)建一個空字典
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;
*/