您的位置:首页 > 理论基础 > 计算机网络

ios中 对网络请求数据文件本地缓存

2012-09-16 10:46 435 查看
之前对ios缓存机制不了解,期间走了很多弯路。以至于在原来公司的第一个项目没有能够提供缓存机制。全部数据都是实时的网络数据。后来经过自己向周围有经验的ios开发人员请教,了解到NSCoder类,以及NSCoding协议。

原来的思路是把本地下载下来的数据写道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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: