自定义model存储

2016-10-16  本文已影响0人  Rasho_Moon

通常app页面需要使用本地化存储来减少用户每次进入请求的等待时间。常用的本地存储方法如NSKeyedArchiver和NSUserDefaults等。但是一般情况下,这些本地存储的类型要求不支持自定义的类型,只支持NSString NSarray NSDictornary等类型。这样可以通过<NSCopying>协议来编码对象和解码对象操作。

创建model遵循<NSCopying>协议

#import <Foundation/Foundation.h> 

@interface Model : NSObject<NSCoding

@property (nonatomic, copy) NSString  *userName;  
@property (nonatomic, copy) NSString  *passWord;  
@property (nonatomic, copy) NSString  *phoneNum; 
 
@end;

#import "Model.h"  
  
@implementation Model  
  
- (void)encodeWithCoder:(NSCoder *)aCoder  
{  
    [aCoder encodeObject:self.userName forKey:@"userName"];  
    [aCoder encodeObject:self.passWord forKey:@"passWord"];  
    [aCoder encodeObject:self.phoneNum forKey:@"phoneNum"]; 
}  
- (instancetype)initWithCoder:(NSCoder *)aDecoder  
{  
    if (self = [super init]) {  
        self.name = [aDecoder decodeObjectForKey:@"userName"];  
        self.Class = [aDecoder decodeObjectForKey:@"passWord"];  
        self.Class = [aDecoder decodeObjectForKey:@"phoneNum"];  
    }  
    return self;  
}  
  
@end  

存储方法

    //获取路径  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"modelTest.plist"];  
    NSFileManager *fileM = [NSFileManager defaultManager];  

    //判断文件是否存在,不存在则直接创建,存在则直接取出文件中的内容  
    if (![fileM fileExistsAtPath:filePath]) {  
        [fileM createFileAtPath:filePath contents:nil attributes:nil];  
    }  
      
    //要保存的自定义模型  
    Model *model= [[Model alloc] init];  
    model.name = @"police";  
    model.userName = @"policeman";
    model.phoneNum = @"110"; 
   
    //添加数组
    [self.dataArr addObject:model];  
  
    //通常情况下的存储方法
    [self.dataArr writeToFile:filePath atomically:YES]; 
    //取数据方法 
    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:filePath]; 
   
   //保存自定义模型存储方法
    [NSKeyedArchiver archiveRootObject:self.dataArr toFile:filePath];  
    //取数据方法 
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
上一篇下一篇

猜你喜欢

热点阅读