数据写在代码里,如果数据经常改,就需要修改代码。造成扩展性低。
因此考虑经常变的数据放入文件中,从文件中读取数据,变动时修改文件
一般可以使用plist文件存储数组或字典类的数据,注意创建plist文件的时候不能取info,与项目信息配置页面重名了。
1 // 数组
2 NSArray *name=@[@"111",@"222",@"333"];
3 BOOL f=[name writeToFile:@"/users/vmmac/desktop/test.plist" atomically:YES];
4 //字典
5 NSDictionary *pp=@{ @"a":@"1",
6 @"b":@"2",
7 @"c":@"3"
8 };
9 BOOL f2=[pp writeToFile:@"/users/vmmac/desktop/pp.plist" atomically:YES];
10 // 数组字典混合着,第一个是值,第二个是字典,第三个又是个数组
11 NSArray *ppp=@[@"1111",
12 @{@"dic1":@"v1",@"dic2":@"v2"},
13 @[@"ttt",@"ggg"] ];
14 BOOL f3=[ppp writeToFile:@"/users/vmmac/desktop/dicAndNSA.plist" atomically:YES];
在桌面生成的plist文件
第三个是数组与字典的混合
下面我们试着从plist文件读取数据。首先我们把刚才创建的其中的一个plist文件拖进项目。拖进来的时候 add to targets记得要打勾。
然后代码里进行读取,接收对象用数组还是字典,取决于该文件的根对象的类型
1 NSString *path=[[NSBundle mainBundle] pathForResource:@"test.plist" ofType:nil];
2 NSArray *arr=[[NSArray alloc]init];
3 arr=[NSArray arrayWithContentsOfFile:path];
4 NSLog(@"%@",arr);