我使用 NSData 在我的应用程序中保留图像。我像这样保存图像(在我的 App Delegate 中):
- (void)applicationWillTerminate:(UIApplication *)application
{
NSLog(@"Saving data");
NSData *data = UIImagePNGRepresentation([[viewController.myViewController myImage]image]);
//Write the file out!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];
[data writeToFile:path_to_file atomically:YES];
NSLog(@"Data saved.");
}
然后我像这样加载它(在我的视图控制器中,下viewDidLoad
):
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];
if([[NSFileManager defaultManager] fileExistsAtPath:path_to_file])
{
NSLog(@"Found saved file, loading in image");
NSData *data = [NSData dataWithContentsOfFile:path_to_file];
UIImage *temp = [[UIImage alloc] initWithData:data];
myViewController.myImage.image = temp;
NSLog(@"Finished loading in image");
}
此代码每次在模拟器上都有效,但在设备上,它似乎永远无法加载回图像中。我很确定它可以保存,但我看不到文件系统。
我在做一些奇怪的事情吗?模拟器访问其目录的方式是否与设备不同?
谢谢!