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;

    }

  • 相关阅读:
    设置共享文件夹大小
    About IConfigurationSectionHandler Interface
    zoj 1050
    SQL Server 数据库优化经验总结
    一、页面输出缓存
    [转]深入解读 ADO.NET 2.0 的十大最新特性
    ASP.NET 缓存学习
    [转]写给ASP.NET程序员:网站中的安全问题
    [转] ASP.NET 性能提升秘诀之管道与进程优化
    实战 SQL Server 2005 镜像配置
  • 原文地址:https://www.cnblogs.com/chendiangoal/p/5404878.html
Copyright © 2011-2022 走看看