一直不太會用NSCache,翻了一下上學期的作業範例,發現有個使用NSCache的方式(using in singleton),先來記錄
1. 從網路上找到了一些關於NSCache的描述,幾乎都會抄Apple官方文件中,來說明NSCache和NSDictionary的差別XD,總之結論:
|- NSCache跟NSDictionary很像
|- 和NSDictionary相同的地方在於都使用key-value的方式
|- 不一樣的地方在於NSCache會在memory比較吃緊的時候釋放
|- Apple中提到如果資料是一次性的資料(例如:user input)則不建議使用NSCache->一次性資料會被destroy
|- 如果資料是可以重複獲得,則盡量使用NSCache來加速獲得資料
2. 網路上的範例(精簡扼要):
|- 宣告NSCache
NSCache *cache = [[NSCache alloc]init];
|- write data to NSCache and disk
- (void)write:(NSData*)data forKey:(NSString*)key{
NSString *filepath = [self filePathForKey:key];
[cache setObject:data forKey:key];
dispatch_async(fileQueue, ^{
[[NSFileManager defaultManager] createFileAtPath:filepath
contents:data
attributes:nil];
});
}
|- read data from NSCache or disk
- (NSData*)readForKey:(NSString*)key{
if(key==nil){
return nil;
}
NSData *cacheData = [cache objectForKey:key];
if(cacheData){
NSLog(@"get data from cache");
return cacheData;
}
else{
NSLog(@"miss data from cache");
NSString *filepath =[self filePathForKey:key];
NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:filepath];
if(fileData){
[cache setObject:fileData forKey:key];
}
return fileData;
}
}
3. 另外放上上學期的作業,在singleton(CLDataSource有比較詳盡用法)
|- CLDataSource.h
|- CLDataSource.m
|- hw2_CityList_SB
沒有留言:
張貼留言