2016-08-04 1 views
0

스냅인과 유사한 앱에서 작업 중이며 이미지 및 비디오의 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]); 
}