I have an in-memory cache that I would like to write out to file on viewWillDisappear and read in back into memory on viewDidLoad. My code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *fileArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSString *filePath = [NSString stringWithFormat:@"%@cache_%d", [fileArray lastObject], self.index];
NSURL *fileUrl = [NSURL URLWithString:filePath];
if ([fileManager fileExistsAtPath:filePath]) {
self.thumbnailsCache = [NSDictionary dictionaryWithContentsOfURL:fileUrl];
}
}
- (void)viewWillDisappear:(BOOL)animated
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *fileArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSString *filePath = [NSString stringWithFormat:@"%@cache_%d", [fileArray lastObject], self.index];
NSURL *fileUrl = [NSURL URLWithString:filePath];
[self.thumbnailsCache writeToURL:fileUrl atomically:YES];
}
Based on some NSLog and debugging, it seems to write the file successfully, but on trying to read it simply says file not found. What am I doing wrong? Thanks.
Edit: self.thumbnailsCache is an NSDictionary of NSData objects.
You’re creating your
filePathincorrectly.fileArrayis an array of URL’s and not NSStrings (which is what your code is assuming).So if you’re taking the last URL as being the cache directory you want to use, you can create the cache file via something like this:
Or, in the context of your code: