美文网首页
ios数据存储2016.6

ios数据存储2016.6

作者: cj2527 | 来源:发表于2016-06-02 16:33 被阅读24次

    1.归档方式

    把记录保存在应用沙盒的某一文件中,进行归档,或者说存档。
    新建一个类CJSearchRecord,继承NSObject,并遵守NSCoding协议
    CJSearchRecord.h文件

    @interface CJSearchRecord : NSObject<NSCoding>
    @property (nonatomic, copy) NSString *beginCity;
    @property (nonatomic, copy) NSString *endCity;
    

    CJSearchRecord.m文件实现两个方法

    //归档、存入档案
    -(void)encodeWithCoder:(nonnull NSCoder *)encoder{
        
        [encoder encodeObject:_beginCity forKey:@"beginCity"];
        [encoder encodeObject:_endCity forKey:@"endCity"];
        
    }
    //解档,打开档案
    -(nullable instancetype)initWithCoder:(nonnull NSCoder *)decoder{
        if (self=[super init]) {
            _beginCity = [decoder decodeObjectForKey:@"beginCity"];
            _endCity =[decoder decodeObjectForKey:@"endCity"];
        }
        return self;
    }
    

    在ViewController.m文件中导入上面创建的文件
    在某一个按钮事件方法中

        //归档,保存搜索记录
        CJSearchRecord *record = [[CJSearchRecord alloc]init];
        //设置值
        record.beginCity = self.beginCity.titleLabel.text;
        record.endCity = self.endCity.titleLabel.text;
        //获取沙盒中的document目录
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        //拼接文件路径
        NSString *filePath = [path stringByAppendingPathComponent:@"searchRecoder.plist"];
        //进行归档
        [NSKeyedArchiver archiveRootObject:record toFile:filePath];
    
    

    在viewDidLoad方法中

     //解档,读档,读取记录
        //获取文件路径
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        NSString *filePath = [path stringByAppendingPathComponent:@"searchRecoder.plist"];
        CJSearchRecord *record = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    

    相关文章

      网友评论

          本文标题:ios数据存储2016.6

          本文链接:https://www.haomeiwen.com/subject/ashkdttx.html