#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
/** 创建字典... */
NSDictionary * dict1 = [NSDictionary dictionary];
NSDictionary * dict2 = [NSDictionary dictionaryWithObject:@"成龙" forKey:@"name"];
// object : key
NSDictionary * dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan", @"name1", @"lisi", @"name2", nil];
NSDictionary * dict4 = [NSDictionary dictionaryWithObjects:@[ @"zhangsan", @"lisi" ] forKeys:@[ @"name1", @"name2" ]];
NSLog(@"%@", dict4);
// 快速创建一个字典 key : object
// key值 不能重复, 如果重复了 也不会报错, 而是 最后添加的将不能够保存到字典中...
NSDictionary * dict5 = @{
@"name1" : @"zhangsan",
@"name2" : @"lisi",
@"name3" : @"zhangsan",
};
NSLog(@"%@", dict5);
/** 其他 */
//获取字典长度 == 键值对个数
NSUInteger count = [dict5 count];
NSLog(@"%lu", count);
//根据key值取出value值
NSString * value1 = [dict5 objectForKey:@"name1"];
NSLog(@"%@", value1);
//根据 value值 取出 所有匹配的 key
NSArray * arr = [dict5 allKeysForObject:@"zhangsan"];
NSLog(@"%@", arr);
/** 字典的遍历 */
// 方法1:
for (NSString * key in [dict5 allKeys]) {
NSLog(@"%@", key);
}
// 可以省略 [dict5 allKeys]
for (NSString * key in dict5) {
NSLog(@"%@", key);
}
// 方法2:
[dict5 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"key = %@ , value = %@", key, obj);
}];
// 方法3:
// enumerate 하나하나 세다
[dict5 enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([key isEqualToString:@"name3"]) {
*stop = YES;
}
else {
NSLog(@"key=%@,value=%@", key, obj);
}
}];
/** Dictionary 简写 */
NSDictionary * dict6 = @{
@"name1" : @"xiangyu",
@"name2" : @"liubang",
@"name3" : @"yuji",
@"name4" : @"xiangshaolong"
};
// 简写形式 获取 value
NSLog(@"%@", dict6[@"name4"]);
// 把Dictionary 保存到 file 中
NSString * path = @"/Users/stone/Desktop";
NSLog(@"%p", path); // 0x1000022f0
path = [path stringByAppendingPathComponent:@"dict.plist"];
NSLog(@"%p", path); // 0x100106210
BOOL isWrite = [dict6 writeToFile:path atomically:YES];
if (isWrite) {
NSLog(@"writing success");
}
else {
NSLog(@"write failed");
}
// 知道指针地址 , 怎么取出指针指向的内容??? 0x7fff5fbff564 这种值 怎么赋值给一个变量??
// 从文件中读取Dictionary
NSDictionary * readDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"%@",readDict);
}
return 0;
}
NSDictionary使用 ... enumerateKeysAndObjectsUsingBlock
最新推荐文章于 2022-06-09 09:26:42 发布