OC中plist文件的读取和写入

plist文件读取,字典数组转模型数组,即:字典转模型

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}
+ (instancetype)heroWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}
+ (NSArray *)heros
{
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil]];
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        [arrayM addObject:[self heroWithDict:dict]];
    }
    return arrayM;
}

 plist文件写入,模型数组转字典数组

        NSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"plist"];
        BOOL success = YES;
        // 归档写入方式,写入的内容不仅仅包括字典数组,上层还有系统针对对象添加的内容,不可取
        // success = [NSKeyedArchiver archiveRootObject:self.heros toFile:path];
        NSMutableArray *arrayM = [NSMutableArray array];
        for (LPKHeros *model in self.heros) {
            NSDictionary *dict = [model dictionaryWithValuesForKeys:@[@"name", @"icon", @"intro"]];
            [arrayM addObject:dict];
        }
        success = [arrayM writeToFile:path atomically:YES];
        if (success) {
            NSLog(@"写入成功!");
        }
原文地址:https://www.cnblogs.com/newbie28/p/4449187.html