NSDictionary使用 ... enumerateKeysAndObjectsUsingBlock

150 篇文章 0 订阅
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值