gpt4 book ai didi

ios - NSData 缓存 iOS

转载 作者:行者123 更新时间:2023-11-30 13:10:37 26 4
gpt4 key购买 nike

我正在开发一个类似 snapchat 的应用程序,我正在尝试缓存图像和视频的 NSData 表示。我尝试使用 NSCache,但这不起作用,每次应用程序进入后台时,缓存上的所有对象都被删除,然后我尝试使用 NSUserDefaults 进行缓存,但这也不是一个好方法。尽管它可以工作并且数据会保留在 NSUserDefaults 中,但它会占用大量内存,而且我已经读到在此类中存储此类对象是不好的做法。除了上面提到的两种之外,您对缓存和持久数据还有哪些建议?

最佳答案

将 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]);
}

关于ios - NSData 缓存 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com