Oc基础之字典

NSDictionary创建

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;

}

简写形式:

快速创建字典

NSDictionary*dict = @{@"name":@"aaa",@"age":@"30"};

NSLog(@"%@,%@",dict[@"name"],dict[@"age"]);

NSDictionary遍历

常规遍历

NSDictionary*dict = @{@"name":@"aaa",@"age":@"30",@"height":@"1.7"};

// 2.1如何获取字典中key和value的个数,在字典中key称之为键, value称之为值

for(inti = 0; i < dict.count; i++) {

//获取字典中所有的key

NSArray*keys = [dictallKeys];

//取出当前位置对应的key

NSString*key = keys[i];

NSString*value = dict[key];

NSLog(@"key = %@,value = %@",key,value);

}

使用OC中的增强for循环来遍历

for(NSString *keyindict) {

NSString *value = dict[key];

NSLog(@"key = %@,value = %@",key,value);

}

使用OC数组的迭代器来遍历

[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

增删改查

创建一个空的字典

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"]);

你可能感兴趣的:(Oc基础之字典)