zoukankan      html  css  js  c++  java
  • 本地缓存

    原来的思路是把本地下载下来的数据写道sqllite数据库中,但是以后用的时间没有办法确定写在数据库中的文件在界面上应该显示的位置。被这个问题纠结了好长时间。周围ios开发人员对缓存又不太熟悉。直到来到现在的公司才有合适的人给解决了这个问题。其实思路并不是很难。

    1.首先,对下载下来的数据(json或xml)经过自己的解析,一般是存为NSArray或者NSDictionary的数据源对象。其中数据源中的每个对象(model)都要实现NSCoding协议。

    Example:我们的项目中有一个表示活动的model类。其中有getter和setter方法,代码就不贴出来了。其中有userid,activityid,messageCount,memberCount等属性。在实现NSCodeing协议后。有两个协议方法要在model类中实现。代码如下:

    #pragma mark – NSCoding

    //keyfor value的key 不贴出

    - (void)encodeWithCoder:(NSCoder*)aCoder {

        [aCoder encodeInt64:self.userIdforKey:1];

        [aCoder encodeInt64:self.activityidforKey:2];

        [aCoder encodeInteger:self.newmessagecountforKey:3];

        [aCoder encodeInteger:self.newmembercountforKey:4];

    }

    - (id)initWithCoder:(NSCoder*)aDecoder {

        self =[superinit];

        if (self) {

            self.userId  = [aDecoder decodeInt64ForKey:1];

            self.activityid =[aDecoder decodeInt64ForKey:2];

            self.newmessagecount =[aDecoder decodeIntegerForKey:3];

            self.newmembercount =[aDecoder decodeIntegerForKey:4];

        }

        returnself;

    }

    注意:如果某个model中有NSMutableArray或NSMutableDictionary的属性,属性中如果存的不是向int,double,NSString等基本类型,也就是说,model中某个属性是其他model或者其他model的集合,则这些子model也要实现NSCoding协议。直到这个链中的属性都被基本类型位置。至于可以编码解码的函数可以去NSCoder.h中去找。

    2.这样最重要的一步已经完成,然后就可以把网络请求返回的数据源存在本地。

    //指定沙盒文件路径[FileOperDocumentFilePath:fileName].不用判断文件是否存在,同名会覆盖。

    - (void)saveMyActionData:(NSMutableArray *)fileArraywithFileName:(NSString*)fileName

    {

        if(fileArray == nil) {

            return;

        }

        NSMutableData*data = [[NSMutableDataalloc] init];

        NSKeyedArchiver*archiver = [[NSKeyedArchiveralloc]initForWritingWithMutableData:data];

        [archiverencodeObject:fileArray forKey:fileName];

        [archiverfinishEncoding];

        [data writeToFile: [FileOperDocumentFilePath:fileName]atomically:YES];

        [archiverrelease];

        [data release];

    }

    3.然后在用的时间从沙盒中把缓存文件load出来。

    - (NSMutableArray *)loadMyActionData:(NSString *)fileName

    {

        NSMutableArray *actionArray = nil;

        NSData*data = [[NSMutableDataalloc] initWithContentsOfFile: [FileOperDocumentFilePath:fileName]];

        if(data) {

            NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];

           actionArray = [unarchiver decodeObjectForKey:fileName];

           [unarchiver release];

        }

        [data release];  

        returnactionArray;

    }

  • 相关阅读:
    ISAPI实现静态页面后并用c#实现分页
    aspx里构造函数里无法使用session,需要重写一个方法放在load里面就能正常使用session了
    记录学习MVC过程,MVC异步请求(五)
    记录学习MVC过程,MVC验证(四)
    记录学习MVC过程,MVC简单路由(三)
    【读书笔记】【韭菜的自我修养】
    【中间件】redis的学习
    【java基础】线程池
    【算法】leetcode刷题 腾讯精选50题 一
    【碎语】让你废掉的七个行为
  • 原文地址:https://www.cnblogs.com/chendiangoal/p/5404878.html
Copyright © 2011-2022 走看看