plist 属性列表 ---数据持久化方式之一

来源:互联网 发布:电脑绘图软件sai 编辑:程序博客网 时间:2024/05/16 10:55

    对于小项目而言,使用SQLite的不常见,一般都是属性列表或者其他的。

建立了一个plist文件必须加 .plist 后缀,不然Type只有Dictionary,需要添加数据。然后根据你添加的数据的规律,需要自己写一个Model模型,等解析这个文件的时候,来接收文件内的内容。



    //plist 属性列表的Root 只有Array Dictionary 两种。

 

    //获取文件路径--跟你建立的plist文件的文件名以及后缀一一对应。

    NSString *path = [[NSBundlemainBundle]pathForResource:@"StudentInformation"ofType:@"plist"];

    

    //获取数据--得看你的.plist文件中最外层是数组还是字典。

   NSArray *array = [NSArrayarrayWithContentsOfFile:path];

    

    //封装成Model对象

   for (NSDictionary *dictin array) {

       Student *student = [Studentnew];

        [student setValuesForKeysWithDictionary:dict];

        

       NSLog(@" %@",student);

    }



===========================


上面一种在解析数据,封装成Model对象的时候,都是先new一个对象,然后再用KVC把一个字典值存入Model对象中,都是走的这两步,接下来的方法,就是优化一下这个创建对象再赋值的方法。就是把KVC赋值给Model对象的过程封装在Model对象的初始化方法中,所以需要我们自己写一个自定义初始化方法。


#import <Foundation/Foundation.h>


#import <CoreGraphics/CoreGraphics.h>



//UIKit框架 包含CoreGraphics框架的。

//但是Foundation框架是不包含的。


@interface Student :NSObject


//atomic 会频繁的加锁解锁,浪费性能

@property(nonatomic,strong)NSString *name;

@property(nonatomic,strong)NSString *gender;

@property(nonatomic,assign)NSInteger age;

@property(nonatomic,assign)NSInteger number;


//自定义初始化方法,方便外界传值,封装KVC

-(instancetype)initWithDictionary:(NSDictionary *)dictionary;



@end

=======================

.m文件

#import "Student.h"


@implementation Student


//id 是不安全的,是任意类型

//instancetype 虽然也是任意类型,但是它可以自动匹配是什么对象。


//id 可以定义一个对象

//instancetype 是不可以的。


//id 是一种动态运行时,也就是在运行时才检测是什么类型。


-(instancetype)initWithDictionary:(NSDictionary *)dictionary

{

   if (self = [superinit]) {

        

        [selfsetValuesForKeysWithDictionary:dictionary];

        

    }

    return self;

}



//开发初期尽量都把这个方法写出来,以便校验。

-(NSString *)description

{

    return [NSStringstringWithFormat:@"%@,%@,%ld,%ld",_name,_gender,_age,_number];

}



@end


==========================


外部解析数据:

//plist 属性列表的Root 只有Array Dictionary 两种。

 

    //获取文件路径--跟你建立的plist文件的文件名以及后缀一一对应。

    NSString *path = [[NSBundlemainBundle]pathForResource:@"StudentInformation"ofType:@"plist"];

    

    //获取数据--得看你的.plist文件中最外层是数组还是字典。

   NSArray *array = [NSArrayarrayWithContentsOfFile:path];

    

    //封装成Model对象

   for (NSDictionary *dictin array) {

       Student *student = [[Studentalloc]initWithDictionary:dict];

        

       NSLog(@" %@",student);

    }




0 0
原创粉丝点击