plist文件是以类似xml形式构造数据,下面我们直接在xcode中创建完成一个plist文件, File-New-File-属性列表
我们可以选择存储类型。这里我构造一组数据,数据中的每个元素都是一个字典,字典中存放着name songName imageName 三个键值。
这样我们的plist文件就完成了,下面来说一说通过kvc的方式来读取plist文件。
kvc的概念简单说下
Key-Value-Coding(KVC)键值编码
我们主要使用的是KVC字典转模型,将plist文件中的数据以数据模型的形式读取。
在构造数据模型时应当使用以下方法 直接设置
- (void)setValuesForKeysWithDictionary:(NSDictionary*)keyedValues;
下面构造一个StarModel
@interface StarModel : NSObject//歌手名@property(nonatomic,copy)NSString *name;//歌曲名@property(nonatomic,copy)NSString *songName;//图片名@property(nonatomic,copy)NSString *imageName;//初始化- (instancetype)initWithStarModelDict:(NSDictionary*)dict;//类方法+ (instancetype)starModelwithDict:(NSDictionary*)dict;@end
下面设置初始化方法,将字典转为模型
@implementation StarModel- (instancetype)initWithStarModelDict:(NSDictionary*)dict { self = [super init]; if (self) { //KVC 字典转模型 [self setValuesForKeysWithDictionary:dict]; } return self;}+ (instancetype)starModelwithDict:(NSDictionary*)dict { return [[StarModel alloc] initWithStarModelDict:dict];}@end
这样我们的模型就构造好了。下面来读取吧。
由于我们plist文件的根节点是一个数组 我们以懒加载的方式来创建这个数组,并将从plist中读取的字典信息以模型的形式存储到数组中。//懒加载- (NSMutableArray*)arrayAllModel { if (!_arrayAllModel) { _arrayAllModel = [NSMutableArray array]; //获得路径并读取plist文件 NSString *starListPath = [[NSBundle mainBundle] pathForResource:@"starList" ofType:@"plist"]; NSArray *array= [NSArray arrayWithContentsOfFile:starListPath]; for (NSDictionary *dic in array) { StarModel *star = [StarModel starModelwithDict:dic]; //存储所有结果 [_arrayAllModel addObject:star]; } } return _arrayAllModel;}
大功告成。现在我们的数组中就都是存放了这些数据模型了。
测试一下数据吧。for (StarModel *model in self.arrayAllModel) { NSLog(@"%@,%@,%@",model.name,model.songName,model.imageName); }