#import <Foundation/Foundation.h>
/*
字典:
key-->value
索引-->文字内容
里面存储的东西都是键值对
*/
int main() {
//不可变,初始化需完成赋值
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"];
id obj = [dict objectForKey:@"name"];
NSLog(@"%@", obj);
NSArray *keys = @[@"name",@"address"];
NSArray *objects = @[@"jack", @"北京"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
id obj1 = [dict2 objectForKey:@"name"];
NSLog(@"%@", obj1);
NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"jack", @"name",
@"北京", @"address",
@"34234234", @"qq", nil];
id obj2 = [dict3 objectForKey:@"qq"];
NSLog(@"%@", obj2);
//建议使用
NSDictionary *dict4 = @{@"name" : @"jack",
@"address" : @"北京",
@"qq" : @"4234234"};
//id obj3 = [dict4 objectForKey:@"address"];
//建议使用
id obj3 = dict4[@"address"];
NSLog(@"%@", obj3);
//返回键值对的个数
NSLog(@"%ld", dict4.count);
//可变字典
NSMutableDictionary *dict5 = [NSMutableDictionary dictionary];
//添加键值对,无序
[dict5 setObject:@"jack" forKey:@"name"];
[dict5 setObject:@"北京" forKey:@"address"];
//重复给key赋值会覆盖以前的值,字典不允许相同的key,允许有相同的object
[dict5 setObject:@"rose" forKey:@"name"];
//删除键值对
//[dict5 removeObjectForKey:@"name"];
//遍历
NSDictionary *dict6 = @{@"name" : @"tom",
@"address" : @"北京",
@"tel" : @"3423424"};
// NSArray *Keys = [dict6 allKeys];
//
// for (int i = 0; i<dict6.count; i++) {
//
// NSString *key = Keys[i];
// NSString *object = dict6[key];
// NSLog(@"%@=%@", key, object);
// }
//block遍历
[dict6 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@-%@", key, obj );
*stop = YES;
}];
return 0;
}
|
|