开发者

How to cache xml lists downloaded from a server?

I am trying to figure out how to cache a list of comic titles that I want to use in a uitableview, and will be updated roughly every week, so instead of loading the list every time the app is launched from the web-server I want to hold onto a cache.. only problem is I'm finding the documentation hard to come across for caching lists like this.

Any example code or suggestions wo开发者_Go百科uld be greatly appreciated :)


  1. You fetch the XML
  2. You parse it to a NSDictionary using NSXMLParser
  3. You serialize and store the dictionary.

@implementation NSDictionary(BinaryPlist)
- (BOOL)writeToBinaryFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile {
    NSString *errorString = nil;
    NSData *data = [NSPropertyListSerialization dataFromPropertyList:self format:NSPropertyListBinaryFormat_v1_0
                                                    errorDescription:&errorString];
    if (errorString) {
        return NO;
    }

    return [data writeToFile:path atomically:useAuxiliaryFile];
}
@end
  1. Then you can define for how long you should consider the cache fresh, or, alternatively, issue HTTP HEAD request and check the Last-Modified header.

- (BOOL)cacheValid:(NSString*)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSDictionary *attrs = [fileManager attributesOfItemAtPath:path error:&error];
    if (!error) {
        NSDate *modDate = [attrs fileModificationDate];
        NSTimeInterval delta = - [modDate timeIntervalSinceNow];
        if (delta < kCacheTTL) {
            return YES;
        }
    }
    return NO;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜