欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NSDictionary

程序员文章站 2024-02-29 23:31:28
...

创建

单个创建

NSDictionary

NSDictionary *dict = [NSDictionary dictionaryWithObjects:(NSArray *) forKeys:(NSArray<id<NSCopying>> *)];
多个创建

NSDictionary

NSDictionary *dict = [NSDictionary dictionaryWithObjects:(NSArray *) forKeys:(NSArray<id<NSCopying>> *)];
快速创建和获取
//创建:键:值,多个创建用逗号隔开
//NSDictionary *dict = @{key:value};
NSDictionary *dict = @{@"name":@"帅逼",@"":@""};
//获取:和C语言数组相似,引号中是键
dict[@"key"];

字典遍历

获取字典key和value的个数(key成为键,value称为值)
//获取键值对个数
[dict count];
使用forin遍历
NSDictionary *dict = @{@"name1":@"帅",@"name2":@"丑"};
for (NSString *key in dict) {
    NSString *value = dict[key];
    NSLog(@"key = %@, value = %@",key, value);
}
迭代器遍历

NSDictionary
NSDictionary

[dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
    NSLog(@"key = %@, value = %@", key, obj);
}];

文件读写

[dict writeToFile:@"/Users/y1shichanganluan/Desktop/info.plist" atomically:YES];

NSDictionary

NSDictionary *newdict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/y1shichanganluan/Desktop/info.plist"];
//字典保存的数据是无序的
[newdict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
    NSLog(@"key = %@, value = %@", key, obj);
}];

注意打印字典和数组并不能直接打印中文,需要重写description方法,使用可变字符串拼接,然后打印


NSMutableDictionary

创建
//空的可修改字典
NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
添加
//增加单个
[dictM setObject:@"" forKey:@""];
//简写
dictM[@"key"] = @"vlaue";
//将一个字典添加进该字典
[dictM setValuesForKeysWithDictionary:@{@"":@"", @"":@""}];
获取

继承与父类

dictM[@"key"];
删除
//删除单个
[dictM removeObjectForKey:@"key"];
//删除多个,需要传入数组
[dictM removeObjectsForKeys:@[@"key1", @"key2"]];
//删除所有
[dictM removeAllObjects];
修改
//使用set给相同的key赋值,新值就会覆盖旧值
[dictM setObject:@"" forKey:@""];

注意

  • 不能使用@{ }创建一个可变的字典
  • 如果是不可变数组,那么key不能相同,后面的会覆盖前面的