我正在开发的应用程序允许用户从他们的相机胶卷中选择一张图像,并将其显示在 UIImageView 中。现在,我在尝试保存数据时遇到了一些问题。我知道我必须将图像转换为 PNG 并保存数据,但我在这样做时遇到了一些问题。一般来说,我对文件保存和 Objective-C 很陌生。这是我正在使用的代码:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}
- (void)applicationDidEnterBackground:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image.image)];
[array addObject:imageData];
[array writeToFile:[self dataFilePath] atomically:YES];
}
- (void)viewDidLoad
{
self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.allowsImageEditing = YES;
self.imgPicker.delegate = self;
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
image.image = [array objectAtIndex:0];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
程序在简单地点击发生这种情况的选项卡时崩溃。调试器指出“'NSInvalidArgumentException',原因:'-[__NSCFData _isResizable]:无法识别的选择器发送到实例 0x16cf50'”。非常感谢任何帮助,谢谢!
最佳答案
好的,首先,您在进入执行这些操作的“选项卡”时遇到此错误,是吗?所以错误应该在你的 viewDidLoad 方法中。其次,您的错误要求选择器错误,因此请找到您使用@selector 的地方。
这是导致错误的问题:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
注意 applicationDidEnterBackground 方法有一个参数 (NSNotification*):
- (void)applicationDidEnterBackground:(NSNotification *)notification {
但您正在向它发送应用程序,这是一个 UIApplication:
UIApplication *app = [UIApplication sharedApplication]
这是我能看到的唯一会给你这个错误的东西。只需将其更改为此,错误就会消失:
- (void)applicationDidEnterBackground:(UIApplication*)application {
开始编辑:
至于保存图像,我不知道你是如何存储数据的,但我会这样做。
- 使用保留的属性来存储图像的数据。
ViewController.h
@interface ViewController
//Add this line
@property(retain) NSData* imageData;
@end
ViewController.m
//Remember to include this line somewhere in this file:
@synthesize imageData;
当您要保存文件时:
- (void)applicationDidEnterBackground:(UIApplication*)application {
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(image.image)];
[self.imageData writeToFile:[self dataFilePath] atomically:YES];
这样就不会丢失数据,也不需要使用数组。只需确保在 viewDidUnload 方法中也添加这一行:
self.imageData = nil;
结束编辑
希望对你有帮助。
关于objective-c - iOS:将图像转换为 PNG 以允许保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9911840/