//
// main.m
// NSDictionary
//
// Created by LiuWei on 15/4/19.
// Copyright (c) 2015年 LiuWei. All rights reserved.
//
#import <Foundation/Foundation.h>
// 字典的创建
void createDict();
// 字典的基本用法
void usagesOfDict();
// 字典的遍历
void ergodic();
int main()
{
@autoreleasepool
{
// createDict();
// usagesOfDict();
ergodic();
}
return 0;
}
#pragma mark - 字典的创建
void createDict()
{
// 不可变字典, 创建具有一对键值对的字典
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSLog(@"%@", dict);
// 以多个键值对形式初始化
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"v1", @"k1",
@"v2", @"k3",nil];
NSLog(@"%@", dict);
// 以一个数组中元素为值, 另一个数组中元素为key创建一个字典, 每个数组中元素必须一一对应
NSArray *value = @[@"11", @"22", @"33", @"44"];
NSArray *keys = @[@1, @2, @3, @4];
dict = [NSDictionary dictionaryWithObjects:value forKeys:keys];
NSLog(@"%@", dict);
}
#pragma mark - 字典的基本用法
void usagesOfDict()
{
NSArray *value = @[@"11", @"22", @"11", @"44"];
NSArray *keys = @[@1, @2, @3, @4];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:value forKeys:keys];
// 返回字典中有多少个键值对
NSLog(@"%ld", dict.count);
// 比较两个字典中键值对是否相同 相同返回 YES, 不同返回 NO
if([dict isEqualToDictionary:dict])
{
NSLog(@"相同");
}
else
{
NSLog(@"不同");
}
// 根据键找到对应的值
NSLog(@"%@ --- %@", [dict objectForKey:@2], @2);
// 将字典写到文件中去
NSString *path = @"/Users/liuwei/Desktop/dict.xml";
BOOL b = [dict writeToFile:path atomically:YES];
if (b) // 写入成功返回 YES 否则返回 NO
{
NSLog(@"写入成功");
}
else
{
NSLog(@"写入失败");
}
// 从文件中读取内容到字典
NSDictionary *dict2 = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"%@", dict2);
// 生成一个数组,存放所有的key
NSArray *allkeys = dict.allKeys;
NSLog(@"%@", allkeys);
// 生成一个数组,存放所有的value
NSArray *allvalues = dict.allValues;
NSLog(@"%@", allvalues);
// 生成一个数组, 存放所有和值 @"11" 对应的key
NSArray *keysForObj = [dict allKeysForObject:@"11"];
NSLog(@"%@", keysForObj);
// 根据数组中的key找到对应的值并存放到一个新生成的数组中 如果没找到用一个id类型对象标记, id对象不能为空
NSArray *ks = @[@1, @3];
NSArray *objs = [dict objectsForKeys:ks notFoundMarker:@-1];
NSLog(@"%@", objs);
}
#pragma mark - 字典的遍历
void ergodic()
{
NSArray *value = @[@"11", @"22", @"11", @"44"];
NSArray *keys = @[@1, @2, @3, @4];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:value forKeys:keys];
// 遍历字典所有的key
for(id key in dict)
{
NSLog(@"key: %@ --- value: %@", key, [dict objectForKey:key]);
}
// 利用迭代器遍历
// key迭代
NSEnumerator *keyEnum = [dict keyEnumerator];
id key = nil;
while (key = [keyEnum nextObject]) {
NSLog(@"key: %@ --- value: %@", key, [dict objectForKey:key]);
}
// value迭代
NSEnumerator *valueEnum = [dict objectEnumerator];
id obj;
while (obj = [valueEnum nextObject]) {
NSLog(@"%@", obj);
}
// block遍历
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"key:%@ ----- value:%@", key, obj);
}];
}