字典

//创建字典  
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];



一个无法新建NSDictionary变量的问题处理: IOS 开发学习26 NSDictionary的一些操作_赋值

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

处理方式 :代码里result1[1]是个byte,ObjectC规定基本数据类型不能直接添加到字典里,可以这样写: @(result1)