//
// main.m
// 字典dictionary
//
// Created by MAC on 15/12/20.
// Copyright © 2015年 MAC. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建字典
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];
NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"1",@"a",@"2",@"a",@"3", nil];
// dict2 = [NSDictionary dictionaryWithDictionary:dict];
//查找Key为2的Value
NSLog(@"%@",[dict objectForKey:@"2"]);
NSLog(@"%@",dict2);
//用两个数组创建字典
NSArray *key = @[@"5",@"6",@"7"];//如果Key重复 只保留第一个VALUE
NSArray *value = @[@"Android",@"IOS",@"cocos2dx"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObjects:value forKeys:key];
NSLog(@"%@",dict3);
for (NSString *a in dict) {
NSLog(@"%@",[dict objectForKey:a]);
}
//key的枚举 也可以object的枚举
NSEnumerator *enu = [dict keyEnumerator];
NSString *a;
while ((a=[enu nextObject])!=nil) {
NSString *value = [dict objectForKey:a];
NSLog(@"%@:%@",a,value);
}
key = dict.allKeys;
value = dict.allValues;
for (NSObject *a in key) {
NSLog(@"%@",a);
}
for (NSObject *a in value) {
NSLog(@"%@",a);
}
//获得所有的key and value
__block int count=0;
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if(++count>1){
*stop = YES;//执行两次 就获取前两对
}
NSLog(@"000%@,%@",key,obj);
}];
//字典写入文件
BOOL b= [dict writeToFile:@"/Users/mac/desktop/test.txt" atomically:YES];
NSLog(@"%d",b);
//从文件读取赋值给字典
dict3 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/mac/desktop/test.txt"];
NSLog(@"ww%@",dict3);
}
return 0;
}