首页 > 其他 > 详细

Object-C学习(七)——Foundation框架(三)

时间:2015-08-14 13:17:44      阅读:284      评论:0      收藏:0      [点我收藏+]

四、NSDictionary和NSMutableDictionary

1、不可变字典NSDictionary

//字典的创建
NSArray *array1 = [NSArray arrayWithObjects:@”zhangsan”,@”zhangfei”,nil];
NSArray *array2 = [NSArray arrayWithObjects:@”lisi”,@”liping”,nil];

NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@”zhang”,array2,@”li”,nil];

//获取字典中的元素个数
NSUInteger count = dic1.count;//or [dic1 count]
NSLog(@”count = %ld”, count);

//创建一个字段是,初始化一个对象
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:array1 forKey:@”zhang”];

//获取字段中所有的key
NSArray  *allkeys = [dic1 allKeys];//or dic1.allKeys

//获取字典中所有的value
NSArray *allvalues = [dic1 allValues];

//通过key获取value
NSArray *array = [dic1 objectForKey:@”zhang”];

/*------------------------------------------------*/
NSDictionary *dic3 = @{@”zhang”:array1,@”li”:array2};
NSLog(@”dic3 = %@” ,dic3);

//取value的语法,字段[“key”]
NSArray *array4 = dic3[“@”zhang”];
NSLog(@” array4 =%@” , array4);

2、可变字典NSMutableDictionary

技术分享
//创建一个可变字典
NSMutableDictionary *md1 = [[NSMutableDictionary alloc] initWithCapacity:3];

//添加元素
[md1 setObject:array1 forKey:@”zhang”];
[md1 setObject:array2 forKey:@”li”];

//将字典dic1中的所有元素添加到md1字典中
[md1 addEntriesFromDictionary:dic1];//字典中相同的key不能重复添加
NSLog(@” md1 = %@” , md1);

//如果添加相同的key,会将原来的value覆盖掉
[md1 setObject:@”zhangsan” forKey:@”zhang”]; 

//删除
[md1 removeObjectForKey:@”zhang”];

//删除所有的元素
[md1 removeAllObjects];

//根据多个key删除对应多个元素
[md1 removeObjectsForKeys:@[@”zhang”,@”li”];
NSLog(@”md1 = %@”, md1);

//遍历字典

//快速遍历
for (NSString *key in md1){
  NSArray * names = [md1 objectForKey:key];
  NSLog(@” names=%@,value=%@”,key, names);
}

//普通遍历
NSArray *allkeys = [md1 allKeys];
for(int i=0;i< allkeys.count;i++){
  NSString *key = allValues[i];
  NSArray *names = md1[key];
  NSLog(@”key=%@,value=%@”,key,names);

}
View Code

 

Object-C学习(七)——Foundation框架(三)

原文:http://www.cnblogs.com/ihoou/p/4729414.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!