2016-08-04 34 views
0

我正在研究類似於snapchat的應用程序,並試圖緩存圖像和視頻的NSData表示。我嘗試過使用NSCache,但這並不奏效,每當應用程序進入後臺時,緩存中的所有對象都被刪除,然後我嘗試使用NSUserDefaults進行緩存,但這也不是一個好方法。雖然它的工作原理和數據一直存在於NSUserDefaults中,但它佔用了大量內存,而且我認爲在這個類中存儲這種類型的對象是不好的做法。除了上面提到的兩點,你對緩存和持久數據有何建議?NSData緩存iOS

回答

0

寫您的NSData到應用程序的文件目錄,當你再次需要在應用程序

將數據寫入應用程序的文檔目錄

//get the path of our apps Document Directory(NSDocumentDirectory) 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

//the path is stored in the first element 

NSString *path = [paths firstObject]; 

//append the name of our file to the path: /path/to/myimage.png 

path = path = [path stringByAppendingPathComponent:@"myimage.png"]; 

//store any errors 

NSError *error; 

// Write NSData to Disk 


BOOL success = [imageData writeToFile:path atomically:YES]; 
if(success){ 
    NSLog(@"Success"); 
}else{ 
    NSLog(@"Error: %@",[error localizedDescription]); 
} 

讀取數據從應用程序的數據讀取它文件目錄

/get the path of our apps Document Directory(NSDocumentDirectory) 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

//the path is stored in the first element 

NSString *path = [paths firstObject]; 

//append the name of our file to the path: /path/to/myimage.png 

path = path = [path stringByAppendingPathComponent:@"myimage.png"]; 

//store any errors 

NSError *error; 

NSData *rawImage = [NSData dataWithContentsOfFile:path 
options:NSDataReadingMappedIfSafe error:nil]; 

if(rawImage){ 
    UIImage *image = [UIImage imageWithData:rawImage]; 
    NSLog(@"%@",image); 
}else{ 
    NSLog(@"Error: %@",[error localizedDescription]); 
}