//
// main.m
// NSDictionary的创建和操作
//
#import <Foundation/Foundation.h>
#pragma mark 字典的创建
void dictCreate(){
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"tom" forKey:@"name"];//只有一对元素的字典
dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"tom", @"20" ,@"male" , nil] forKeys:[NSArray arrayWithObjects:@"name", @"age", @"sex", nil]];//用数组分别做键和值
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"tom", @"name" ,
@"male", @"sex" ,
@"22", @"age", nil];//值=》键
NSLog(@"%@", dict);
}
#pragma mark 字典的使用
void dictUse(){
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"tom", @"name" ,
@"male", @"sex" ,
@"22", @"age", nil];
NSArray *arr = [dict allKeys];//取出所有的key
arr = [dict allValues];//取出所有的值
id obj = [dict objectForKey:@"age"];//根据键取值
arr = [dict objectsForKeys:[NSArray arrayWithObjects:@"name", @"sex", @"class", nil] notFoundMarker:@"notFound"];//根据数组中的键取值,没有的以notFound替换
NSInteger len = dict.count;//键值对数
NSString *path = @"/Users/greezen/Desktop/dict.xml";
if ([dict writeToFile:path atomically:YES]){
NSLog(@"写入文件成功");
}else{
NSLog(@"写入文件失败");
}
dict = [NSDictionary dictionaryWithContentsOfFile:path];//从文件中读取以创建字典
NSLog(@"%@", dict);
}
#pragma mark 字典的遍历
void dictFor(){
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"tom", @"name" ,
@"male", @"sex" ,
@"22", @"age", nil];
//法一
for (id key in dict) {
NSLog(@"%@=>%@", key, [dict objectForKey:key]);
}
//法二
NSEnumerator *enu = [dict keyEnumerator];
id key = nil;
while (key = [enu nextObject]) {
NSLog(@"%@->%@", key, [dict objectForKey:key]);
}
enu = [dict objectEnumerator];
id obj = nil;
while(obj = [enu nextObject]){
NSLog(@"%@", obj);
}
//法三
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@-->%@", key, [dict objectForKey:key]);
}];
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
//dictCreate();
//dictUse();
dictFor();
}
return 0;
}