NSDictionary創(chuàng)建
NSDictionary*dict = [NSDictionarydictionaryWithObject:@"aaa"forKey:@"name"];
NSString*name = [dictobjectForKey:@"name"];//把name作為鍵值
NSLog(@"%@",name);//不妨輸出看看打印出的樣子
NSDictionary*dict = [NSDictionarydictionaryWithObjects:@[@"aaa",@"20",@"1.7"]forKeys:@[@"name",@"age",@"height"]];
NSString*name = [dictobjectForKey:@"name"];
NSString*age = [dictobjectForKey:@"age"];
NSString*height = [dictobjectForKey:@"height"];
NSLog(@"%@,%@,%@",name,age,height);
輸出:
{
age = 20;
height = "1.7";
name = aaa;
}
簡寫形式:
快速創(chuàng)建字典
NSDictionary*dict = @{@"name":@"aaa",@"age":@"30"};
NSLog(@"%@,%@",dict[@"name"],dict[@"age"]);
NSDictionary遍歷
常規(guī)遍歷
NSDictionary*dict = @{@"name":@"aaa",@"age":@"30",@"height":@"1.7"};
// 2.1如何獲取字典中key和value的個數(shù),在字典中key稱之為鍵, value稱之為值
for(inti = 0; i < dict.count; i++) {
//獲取字典中所有的key
NSArray*keys = [dictallKeys];
//取出當(dāng)前位置對應(yīng)的key
NSString*key = keys[i];
NSString*value = dict[key];
NSLog(@"key = %@,value = %@",key,value);
}
使用OC中的增強for循環(huán)來遍歷
for(NSString *keyindict) {
NSString *value = dict[key];
NSLog(@"key = %@,value = %@",key,value);
}
使用OC數(shù)組的迭代器來遍歷
[dict enumerateKeysAndObjectsUsingBlock:^(id_Nonnullkey,id_Nonnullvalue,BOOL*_Nonnullstop) {
NSLog(@"key = %@,value = %@",key,value);
}];
字典排序
字典輸出來的是無序的啡专,按照key首字母英文單詞排序
NSDictionary文件讀寫
字典文件寫入
NSDictionary*dict = @{@"name":@"aaa",@"age":@"30",@"height":@"1.7"};
[dictwriteToFile:@"/Users/kobi/Desktop/abc.plist"atomically:YES];
字典文件讀出
NSDictionary*newDict = [NSDictionary ? dictionaryWithContentsOfFile:@"/Users/kobi/Desktop/abc.plist"];
NSLog(@"%@",newDict);
NSMutableDictionary
增刪改查
創(chuàng)建一個空的字典
NSMutableDictionary*dictM = [NSMutableDictionary ?dictionary];
添加鍵值
[dictMsetObject:@"lnj"forKey:@"name"];
NSLog(@"%@",dictM);
[dictMsetValuesForKeysWithDictionary:@{@"age":@"30",@"height":@"1.7"}];
NSLog(@"%@",dictM);
刪除鍵值
[dictMremoveObjectForKey:@"name"];
NSLog(@"%@",dictM);
[dictMremoveObjectsForKeys:@[@"age",@"height"]];
NSLog(@"%@",dictM);
替換元素
[dictMsetObject:@"99"forKey:@"age"];
dictM[@"age"] =@"89";
NSLog(@"%@",dictM);
獲取元素
NSLog(@"name = %@",dictM[@"name"]);