本文主要是介绍Objective-C字典NSDictionary与可变字典NSMutableDictionary使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//通过类对象创建字典NSDictionary *dic = [[NSDictionary alloc] initWithObjects:@[@1,@2,@3] forKeys:@[@"A",@"B",@"C"]];//通过键取字典中值NSLog(@"count:%lu,A:%@,B:%@,C:%@",dic.count,[dic objectForKey:@"A"],[dic objectForKey:@"B"],[dic objectForKey:@"C"]);//一值一键,先值后键NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@1,@"A",@2,@"B",@3,@"C",@4,@"D", nil];//value,key//遍历值for (id v in dic1.objectEnumerator) {NSLog(@"%@",v);}//遍历键for (id v in dic1.keyEnumerator) {NSLog(@"%@",v);}//通过现有字典创建可扩展字典NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:dic1];//向可扩展字典中添加键值对[mdic setObject:@5 forKey:@"E"];//创建不可扩展字典NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:@[@6,@7,@8] forKeys:@[@"F",@"G",@"H"]];//向可扩展字典中添加现有字典[mdic addEntriesFromDictionary:dic2];//遍历字典for (id x in mdic) {NSLog(@"%@",x);}//创建可扩展集合对象NSMutableArray *numArray = [[NSMutableArray alloc] init];//向集合添加数据for (int i=0; i<100; i++) {//创建数字对象NSNumber *num1 = [[NSNumber alloc]initWithInt:i];[numArray addObject:num1];}//正向遍历集合for (id n in numArray.objectEnumerator) {NSLog(@"%@",n);}//反向遍历集合for (id n in numArray.reverseObjectEnumerator) {NSLog(@"%@",n);}//大数使用NSDecimalNumber[numArray removeAllObjects];for (int i=1; i<101; i++) {//创建数字对象NSNumber *num1 = [[NSDecimalNumber alloc]initWithInt:i*999999];[numArray addObject:num1];}//正向遍历集合for (id n in numArray.objectEnumerator) {NSLog(@"%@",n);}//反向遍历集合for (id n in numArray.reverseObjectEnumerator) {NSLog(@"%@",n);}
这篇关于Objective-C字典NSDictionary与可变字典NSMutableDictionary使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!