键值对 key(一般为字符串对象)---vaule(必须是对象)
Person *p1 =[[Person alloc ]init];
Person *p2 =[[Person alloc ]init];
Person *p3 =[[Person alloc ]init];
NSDictionary
创建一个字典
NSDictionary *dic =@{@"p1":p1,@"p2":p2,@"p3":p3};
通过键访问值
Person *p4 = [dic objectForKey:@"p1"];
遍历字典
NSArray *allKeys = [dic allKeys];
NSLog(@"allkey: %@",allKeys);
NSArray *allValue = [dic allValues];
NSLog(@"allValue: %@",allValue);
for (NSString * key in allKeys) {
NSLog(@"%@ %@",key ,[dic objectForKey:key]);
}
获取键值对个数
NSLog(@"%ld",dic.count);
NSMutableDictionary
创建可变字典
NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:0];
添加值
[dic setObject:p1 forKey:@"p1"];
[dic setObject:p2 forKey:@"p2"];
[dic setObject:p3 forKey:@"p3"];
NSArray *allKeys = [dic allKeys];
更改某一个值
[dic setObject:p3 forKey:@"p1"];
删除某一个值
[dic removeObjectForKey:@"p1"];
全部删除值
[dic removeAllObjects];