您的位置:首页 > 其它

字典(NSDictionary)及可变字典(NSMutableDictionary)基础学习

2015-11-05 21:03 483 查看
#pragma mark -----------不可变字典-----------

//字典 NSDictionary

//使用便利构造器来创建一个字典

//wangwu : Value -->是对象 -->可以重复

//name : key --> 不可以重复

//的字典是由键值对组成,也就是(key - value),而且字典内的存储是无序的

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"wangwu",@"name",@"man",@"sex", nil];

NSLog(@"dict = %@",dict);

//将数组对象放入字典

NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"zhaosi",@"男",nil] forKeys:

[NSArray arrayWithObjects:@"name",@"sex" ,nil]];

NSLog(@"dict1 = %@",dict1);

//获取字典对象的所有key: allKeys

NSLog(@"allkeys = %@",[dict allKeys]);

//获取字典所有对象的value: allvalues

NSLog(@"allValues = %@ ",[dict allValues]);

//字典是通过我们的Key来找到她对于的Value;

NSLog(@"name = %@ ", [dict1 objectForKey:@"name"]);

//打印出name对于的value : zhaosi

#pragma mark ------------可变字典-------------

//创建可变字典

NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"heiliu",@"name",[NSNumber numberWithInt:20],@"age", nil];

//NSNumber numberWithInt 将数字转换为NSNumber类型

//添加/修改

//如果字典中没有设置的key值,就向字典添加元素,如果key存在就修改对于key值上得 value数据

[mutableDict setObject:@"beijing" forKey:@"address"];

//此时key = address 在字典中没有,就创建key-value 添加到字典

NSLog(@"mutableDict1 = %@ ",mutableDict);

[mutableDict setObject:@"tianjing" forKey:@"address"];

//此时key = address 在字典中存在,所有就修改key对于的value,这里把 beijing 修改为 :tianjing;

NSLog(@"mutableDict2 = %@",mutableDict);

//将age对于的value置空

[mutableDict setValue:nil forKey:@"age"];

NSLog(@"mutableDict3 = %@",mutableDict);

//区别于@"nil"

[mutableDict setValue:@"nil" forKey:@"age"];

NSLog(@"mutableDict4 = %@",mutableDict);

//删除

//全部删除,将字典中元素全部删除,打印为空

// [mutableDict removeAllObjects];

// NSLog(@"mutableDict5 = %@",mutableDict);

//个别删除,通过key删除(将上面全部删除代码注释掉,不然打印不出)

[mutableDict removeObjectForKey:@"age"];

NSLog(@"mutableDict6 = %@",mutableDict);

//替换

//将字典中全部键值,替换为输入的键值

[mutableDict setDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"100",@"num", nil]];

NSLog(@"mutableDict7 = %@",mutableDict);

//通过key值,快速枚举字典中得值

//str里面是key的值,是NSString类型

for (NSString *str in mutableDict) {

NSLog(@"%@:%@",str,[mutableDict objectForKey:str]);

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