首页 > 代码库 > cocoa foundation笔记-3
cocoa foundation笔记-3
//Foundation中的字典NSDictionary是由键-值对组成的数据集合。key(键)的值必须是唯一的 /*****************不可变字典*****************/ //字典的初始化 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"]; //输出:{key = value} NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:@"v1", @"k1", @"v2", @"k2", @"v3", @"k3", nil]; NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2]; //获取字典的数量 int count = [dic2 count]; //输出:count=3(有3组键-值对) //根据键名获取其值 NSString *string = [dic2 objectForKey:@"k2"]; //输出:string=v2 //获取字典的所有key和value NSArray *keyArray = [dic2 allKeys]; //输出:keyArray={k1,k2,k3} NSArray *valueArray = [dic2 allValues]; //输出:valueArray={v1,v2,v3} /****************可变字典*********************/ //创建一个字典 NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"v1", @"k1", @"v2", @"k2", @"v3", @"k3", nil]; //添加键-值对 //方式一 NSDictionary *dic4 = [NSDictionary dictionaryWithObject:@"v4" forKey:@"k4"]; [mutableDic addEntriesFromDictionary:dic4]; //方式二 【mutableDic setValue:@"object" forKey:@"k5"]; //创建一个空的可变字典 NSMutableDictionary *mutableDic2 = [NSMutableDictionary dictionary]; [mutableDic2 setDictionary:mutableDic]; //NSMutableDictionary *mutableDic2 = [NSMutableDictionary dictionaryWithObject:@"one" forKey:@"k"]; //根据键名删除元素 [mutableDic removeObjectForKey:@"k3"]; //删除一组键值对 NSArray *keys = [NSArray arrayWithObjects:@"k1", @"k2", @"k3", nil]; [mutableDic removeObjectsForKeys:keys]; //删除所有元素 [mutableDic removeAllObjects]; /****************遍历字典*************************/ //一般遍历 for(int index=0; index<[mutableDic count]; index++) { NSString *object = [mutableDic objectForKey:[[mutableDic allKeys] objectAtIndex:index]]; NSLog(@"%@", object); } //快速枚举 for(id key in mutableDic) { NSString *object = [mutableDic objectForKey:key]; NSLog(@"%@", object); } //通过枚举类型遍历 NSEnumerator *enumerator = [mutableDic keyEnumerator]; id key = [enumerator nextObject]; while(key) { id object = [mutableDic objectForKey:key]; NSLog(@"%@", object); key = [enumerator nectObject]; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。