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

IOS 开发学习26 NSDictionary的一些操作

2015-05-28 14:54 441 查看

字典

//创建字典
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
//创建多个值字典
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
@"value4", @"key4",
nil];



从字典创建
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2];

//取值
NSLog(@"key3 value :%@", [dic3 objectForKey:@"key3"]);

//元素数量
NSLog(@"dic count :%d", dic3.count);

//键集合数组
NSArray *keys = [dic3 allKeys];

//值数组
NSArray *values = [dic3 allValues];

可变字典

//可变字典
NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
@"mvalue1", @"mkey1",
@"mvalue2", @"mkey2", nil];
//创建可变字典 设定初始长度 用的时候超出也没关系
[NSMutableDictionary dictionaryWithCapacity:10]

//添加字典
[mutableDic addEntriesFromDictionary:dic3];

//添加键值对
[mutableDic setValue:@"set1" forKey:@"setKey1"];
//添加数据
[dictionary setObject:@"雨松MOMO" forKey:@"name"];
//取值
NSObject *object = [dictionary objectForKey:@"name"];


//字典整体赋值
[mutableDic setDictionary:dic2];

//删除键
[mutableDic removeObjectForKey:@"key1"];

//遍历1
for(id key in mutableDic) {
NSLog(@"key :%@  value :%@", key, [mutableDic objectForKey:key]);
}

//遍历2
NSEnumerator *enumerator = [mutableDic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
NSLog(@"enumerator :%@", [mutableDic objectForKey:key]);
key = [enumerator nextObject];
}

//清空
[mutableDic removeAllObjects];

Plist操作

//读取
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

//写入
[dic writeToFile:testPath atomically:YES];


更多参照这里: http://blog.csdn.net/xundh/article/details/45716015
一个无法新建NSDictionary变量的问题处理:



提示: Thread n:EXC_BAD_ACCESS(code=1,address=0x1)

处理方式 :代码里result1[1]是个byte,ObjectC规定基本数据类型不能直接添加到字典里,可以这样写:
@(result1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: