#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建字典
//key和value值必须是对象
NSDictionary *dict1 = [NSDictionary dictionary];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"zhangsan" forKey:@"zs"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2", nil];
NSLog(@"%@",dict1);
NSLog(@"%@",dict2);
NSLog(@"%@",dict3);
//key值不能重复,重复不会报错-最后添加的不能保存到字典中
NSDictionary *dict4 = @{@"zs":@"zhangsan",@"ls":@"lisi",@"bz":@"banzhang",@"zs":@"zhaosi"};
NSLog(@"%@",dict4);
NSLog(@"%lu",dict4.count);//获取字典长度
NSString *s1 = [dict4 objectForKey:@"zs"];//根据key取出value值
NSLog(@"%@",s1);
//字典的遍历
// for (NSString *key in dict4) {
// NSLog(@"key = %@,value = %@",key,[dict4 objectForKey:key]);
// }
[dict4 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"%@ = %@",key,obj);
}];
}
return 0;
}
最经典的应用 lbs
#import <Foundation/Foundation.h>
void test1(){
//简写定义字典
NSDictionary *dict1 = @{@"zbz":@"zhangbozhi",@"cgx":@"chenguanxi",@"xzmly":@"hello"};
//简写获取value
NSLog(@"%@",dict1[@"zbz"]);
//字典写入文件
// BOOL isWrite = [dict1 writeToFile:@"/users/donglizheng/Desktop/dict1.plist" atomically:YES];
// if (isWrite) {
// NSLog(@"写入成功");
// }
NSDictionary *readDict1 = [NSDictionary dictionaryWithContentsOfFile:@"/users/donglizheng/Desktop/dict1.plist"];
NSLog(@"%@",readDict1);
}
void test2(){
NSArray *lnArr = [NSArray arrayWithObjects:@"dalian",@"shenyang", nil];
NSArray *hbArr = [NSArray arrayWithObjects:@"baoding",@"shijiazhuang", nil];
NSDictionary *citys = [NSDictionary dictionaryWithObjectsAndKeys:lnArr,@"ln",hbArr,@"hb", nil];
NSLog(@"citys = %@",citys);
[citys writeToFile:@"/users/donglizheng/Desktop/citys.plist" atomically:YES];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDictionary *cityDict1 = [NSDictionary dictionaryWithContentsOfFile:@"/users/donglizheng/Desktop/citys.plist"];
[cityDict1 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
// NSLog(@"key = %@,value = %@",key,obj);
for (NSString *s1 in obj) {
NSLog(@"city = %@",s1);
}
}];
NSArray *lnArr = cityDict1[@"ln"];
NSLog(@"%@",[lnArr lastObject]);
}
return 0;
}
|