黑马程序员技术交流社区
标题:
有谁知道NSDictionary怎么用?
[打印本页]
作者:
ios学者
时间:
2015-12-10 00:29
标题:
有谁知道NSDictionary怎么用?
有谁知道NSDictionary怎么用?
作者:
王晓亮
时间:
2015-12-10 07:38
!!!!!!
作者:
董立正
时间:
2015-12-10 18:36
#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;
}
作者:
Flowerkanzhe
时间:
2015-12-10 21:53
董立正 发表于 2015-12-10 18:36
#import
int main(int argc, const char * argv[]) {
这仁兄说得对
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2