@fiy-fish
2015-07-15T20:17:51.000000Z
字数 2043
阅读 1375
Objective-c
// main.m
// day05-04-字典
//
// Created by Aaron on 15/7/7.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
//字典
//键值对
//key----value
//键值对成对出现
//一一对应
//哈希
//key必须是唯一的
//value可以是多个
//里面存储的都只能是对象
//NSDictionary
//NSMutableDictionary
#if 0
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDictionary *dic = [[NSDictionary alloc] init];
//用键值对来初始化字典
//注意:值在前,键在后,成对出现
//没有顺序
NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@1,@"one",@2,@"two",@3,@"three", nil];
NSLog(@"%@",dic1);
NSArray *valueArray = @[@1,@2,@3,@4];
NSArray *keyArray = @[@"one",@"three",@"four",@"two"];
//用键值对数组来初始化字典
NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray];
NSLog(@"%@",dic2);
NSDictionary *dic3 = [[NSDictionary alloc] initWithDictionary:dic2];
//NSDictionary *dic4 = [NSDictionary dic]
//类方法创建字典
//2.0新特性
//@{key:value,key:value....}
}
return 0;
}
#endif
#if 0
int main()
{
//常用的方法
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@1,@"three",@2,@"two", nil];
//获取键值对的个数
NSInteger count = [dic count];
NSLog(@"%ld",count);
//获取key对应的value
id obj = [dic objectForKey:@"one"];
NSLog(@"%@",obj);
//获取值对应的键
NSArray *keys = [dic allKeysForObject:@1];
NSLog(@"%@",keys);
//获取所有的键
NSArray *allKeys = [dic allKeys];
NSLog(@"%@",allKeys);
//获取所有的值
NSArray *objs = [dic allValues];
NSLog(@"%@",objs);
}
#endif
//字典的遍历
#if 0
int main()
{
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@1,@"three",@2,@"two", nil];
//for in快速遍历
for(id obj in dic)
{
//遍历出来的是key
NSLog(@"%@",obj);
}
NSEnumerator *enumerator = [dic keyEnumerator];
enumerator = [dic objectEnumerator];
id obj = nil;
while(obj = [enumerator nextObject])
{
NSLog(@"%@",obj);
}
}
#endif
int main()
{
//可变字典
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//增删改
//添加键值对其实是设置一对键值对
[dic setObject:@10 forKey:@"ten"];
NSLog(@"%@",dic);
//从另外一个字典里将键值对添加到当前字典
[dic addEntriesFromDictionary:@{@"two":@2}];
NSLog(@"%@",dic);
//修改
[dic setObject:@22 forKey:@"two"];
NSLog(@"%@",dic);
//删除
//删掉key所对应的键值对
// [dic removeObjectForKey:@"two"];
// [dic removeObjectsForKeys:@[@"ten",@"two"]];
[dic removeAllObjects];
[dic setDictionary:@{}];
NSLog(@"%@",dic);
}