您的位置:首页 > 移动开发 > IOS开发

IOS_OC_字典

2015-09-07 17:39 302 查看
#import <Foundation/Foundation.h>

int main(int argc,
const char * argv[]) {

//字典(NSDictionary)

//

//字典的特性:

//1.一个key只能对应一个值

//2.所有的key不能重复

//3.一个值可以有多个key对应

NSDictionary *dic =[
NSDictionary
dictionaryWithObjectsAndKeys:@"value",@"key",@"value1",@"key1",
nil];

NSLog(@"%@",dic);

// 获取dic中值(value)数量

NSLog(@"%ld",dic.count);

// 获取object(对应得值)

NSString *ob = [dic
objectForKey:@"key1"];

NSLog(@"%@",ob);

//

//可变字典

NSMutableDictionary *mutableDic = [NSMutableDictionary
dictionary];

//在字典里添加一个新的键值对

//如果字典中没有给定的key,就增加一个新的键值对

//如果已经有key,就覆盖掉原来的对象

[mutableDic setObject:@"value"
forKey:@"key"];

[mutableDic setObject:@"value1"
forKey:@"key"];

NSLog(@"%@",mutableDic);

[mutableDic addEntriesFromDictionary:dic];

NSLog(@"%@",mutableDic);

//移除键值对

NSArray *keys = [NSArray
arrayWithObjects:@"key1",@"key3",
nil];

[mutableDic removeObjectForKey:keys];

NSLog(@"%@",mutableDic);

// 字典的遍历

for (NSString *key
in dic) {

//每次取出的都是字典的key

NSLog(@"%@",key);

//循环中需要获取value

NSLog(@"%@",[dic
objectForKey:key]);

}

// 不可变集合

//数组() 有序 下标

//字典{} 无序 key key value

//集合 {()}无序

NSSet *set =[
NSSet setWithObjects:@"a",@"b",@"c",@"a",
nil];

NSLog(@"%@",set);

//元素个数

NSLog(@"%ld",set.count);

//取值方式(随便取值)

NSString *str = [set
anyObject];

NSLog(@"%@",str);

//把集合中的对象放到一个数组里

NSArray *setArr = [set
allObjects];

NSLog(@"%@",setArr);

//可变集合增加一个对象

//移除一个对象

NSMutableSet *mutableSet = [NSMutableSet
setWithObjects:@"a",@"d",@"e",nil];

//取并集

[mutableSet unionSet:set];

NSLog(@"%@",mutableSet);

//去除重复

[mutableSet minusSet:set];

NSLog(@"%@",mutableSet);

//取交集

[mutableSet intersectSet:set];

NSLog(@"%@",mutableSet);

//数组排序

NSMutableArray *arr = [NSMutableArray
arrayWithObjects:@"b",@"z",@"a",@"n",nil];

//sort

[arr sortUsingSelector:@selector(compare:)];

NSLog(@"%@",arr);

//快速创建对象

//@"asdfrej";

//快速产生一个不可变数组

NSArray *sArr =
@[@"a",@"c",@"c"];

NSLog(@"%@",sArr);

//快速产生字典

NSDictionary *dic1=
@{@"key":@"value",@"key1":@"value1"};

NSLog(@"%@",dic1);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: