0

我对编程很陌生,我直接进入了一个项目(我知道这不是最聪明的事情,但我边走边学)。我正在编写的应用程序有 10 个 UIImageViews,它们显示来自用户相机胶卷的图片。我使用的代码需要每个 UIImageViews 都有标签。我目前正在使用 NSData 来保存数组图像,效果很好,但是我不能再使用这种方法了,因为 NSData 不支持使用标签。我也不能使用 NSUserDefaults,因为我不能将图像保存到 plist。这是我尝试执行此操作的方式(使用 NSData 方法,该方法有效,但我必须对其进行编辑,以便我的标签有效。)

这是我当前的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
    if (imageView.image == nil) {
        imageView.image = img;

        [self.array addObject:imageView.image];

        [picker dismissModalViewControllerAnimated:YES];
        [self.popover dismissPopoverAnimated:YES];
        return;

    }

    if (imageView2.image == nil) {
        imageView2.image = img;
        NSLog(@"The image is a %@", imageView);
        [self.array addObject:imageView2.image];

        [picker dismissModalViewControllerAnimated:YES];
        [self.popover dismissPopoverAnimated:YES];
        return;
    }
    ...


- (void)applicationDidEnterBackground:(UIApplication*)application {
    NSLog(@"Image on didenterbackground: %@", imageView);

    [self.array addObject:imageView.image];
    [self.array addObject:imageView2.image];

    [self.user setObject:self.array forKey:@"images"];
    [user synchronize];

}

- (void)viewDidLoad
{
    self.user = [NSUserDefaults standardUserDefaults];
    NSLog(@"It is %@", self.user);
    self.array = [[self.user objectForKey:@"images"]mutableCopy];
    imageView.image = [[self.array objectAtIndex:0] copy];
    imageView2.image = [[self.array objectAtIndex:1] copy];    

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:app];

    [super viewDidLoad];

}

任何有关如何编辑此代码的帮助或建议,以便我可以在使用标签的同时保存图像,非常感谢,谢谢!

编辑:这是我更新的代码:

       -(IBAction)saveButtonPressed:(id)sender {
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];

    for (UIImageView *imageView in self.array) {

        NSInteger tag = self.imageView.tag;
        UIImage *image = self.imageView.image;
        NSString *imageName = [NSString stringWithFormat:@"Image%i.png",tag];

        NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    }
NSLog(@"Saved Button Pressed");
}



- (void)applicationDidEnterBackground:(UIApplication*)application {

}


-(void)viewDidLoad {

    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];

    NSArray *docFiles = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:docsDir error:NULL];

    for (NSString *fileName in docFiles) {

        if ([fileName hasSuffix:@".png"]) {
            NSString *fullPath = [docsDir stringByAppendingPathComponent:fileName];
            UIImage *loadedImage = [UIImage imageWithContentsOfFile:fullPath];

            if (!imageView.image) {
                imageView.image = loadedImage;
            } else {
                imageView2.image = loadedImage;
            }
        }
    }
}
4

3 回答 3

4

您需要使用“快速枚举”来解析数组的对象,并将每个对象按顺序写入磁盘。首先,您需要将 UIImageView 对象而不是 UIImageView 的 UIImage 属性添加到数组中,以便您可以恢复标签。所以不要写

[self.array addObject:imageView.image];

这将是

[self.array addObject:imageView];

尝试遵循我的代码。我在每一行都插入了注释以提供帮助。

-(void)applicationDidEnterBackground:(UIApplication *)application {
    //Obtain the documents directory
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainmask,YES) objectAtIndex:0];
    //begin fast enumeration
    //this is special to ObjC: it will iterate over any array one object at a time
    //it's easier than using for (i=0;i<array.count;i++)
    for (UIImageView *imageView in self.array) {
        //get the imageView's tag to append to the filename
        NSInteger tag = imageView.tag;
        //get the image from the imageView;
        UIImage *image = imageView.image;
        //create a filename, in this case "ImageTAGNUM.png"
        NSString *imageName = [NSString stringWithFormat:@"Image%i.png",tag];
        //concatenate the docsDirectory and the filename
        NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    }
}

要从磁盘加载图像,您必须查看 viewDidLoad 方法

-(void)viewDidLoad {
    //get the contents of the docs directory
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainmask,YES) objectAtIndex:0];
    //Get the list of files from the file manager
    NSArray *docFiles = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:docsDir error:NULL]);
    //use fast enumeration to iterate the list of files searching for .png extensions and load those
    for (NSString *fileName in docFiles) {
        //check to see if the file is a .png file
        if ([fileName hasSuffix:@".png"]) {
            NSString *fullPath = [docsDir stringByAppendingPathComponent:fileName];
            UIImage *loadedImage = [UIImage imageWithContentsOfFile:fullPath];
            //you'll have to sort out how to put these images in their proper place
            if (!imageView1.image) {
                imageView1.image = loadedImage;
            } else {
                imageView2.image = loadedImage;
            }
        }
    }
}

希望这可以帮助

您需要注意的一件事是,当应用程序进入后台时,它有大约 5 秒的时间来清理其行为,然后才暂停。UIPNGRepresentation() 函数需要大量时间并且不是即时的。你应该意识到这一点。在其他地方编写这些代码并在应用程序后台执行之前可能会更好。FWIW

于 2012-04-13T20:25:20.467 回答
1

首先,您的 for 循环中仍然存在问题。

for (UIImageView *imageView in self.array) {
    NSInteger tag = self.imageView.tag;
    UIImage *image = self.imageView.image;
    // ...
}

在进行任何其他更改之前,您必须了解原因。 imageView是您的for 循环控制变量,它在循环的每次迭代中都会发生变化。 self.imageView是另一回事。它是附加到您的 viewController 的 10 个 imageView 中的第一个。每次循环循环时,它都会查看第一个 imageView,并且只查看第一个。

至于为什么保存不起作用,可能是因为其他地方的数组不起作用。添加一些日志记录以确保数组中有某些内容,并且它具有您期望的尽可能多的元素。

-(IBAction)saveButtonPressed:(id)sender {
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];

    // Log to make sure the views expected have previously been stored.
    // If the array is empty, or shorter than expected, the problem is elsewhere.
    NSLog(@"Image view array before saving = %@", self.array);

    for (UIImageView *imageViewToSave in self.array) {

        NSInteger tag = imageViewToSave.tag;
        UIImage *image = imageViewToSave.image;
        NSString *imageName = [NSString stringWithFormat:@"Image%i.png",tag];

        NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];

        // Log the image and path being saved.  If either of these are nil, nothing will be written.
        NSLog(@"Saving %@ to %@", image, imagePath);

        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:NO];
    }
    NSLog(@"Save Button Pressed");
}
于 2012-04-14T03:31:20.263 回答
1

您可以使用 [NSbundle Mainbundel] 来存储该图像。

获取路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *documentsDirectory = [paths objectAtIndex:0];
于 2012-04-11T03:44:18.423 回答