单击按钮时如何保存图像

时间:2014-02-21 03:40:38

标签: ios objective-c

我正在创建一个应用程序,有一个保存按钮可以将图像保存在另一个视图控制器中。即,按下一个视图控制器上的保存按钮,图像应该保存在另一个视图控制器上,直到我手动处理我的应用程序中的删除按钮,它才会删除。

我尝试使用NSUserDefault但是如果我关闭应用程序并重新打开它,则会自动删除保存的图像。如何在用户手动完成之前保留该图像。

//view controller 1 
if(count == 0) {
    [testArray addObject:imageArray[0]];
    [testArray addObject:imageArray[1]];
}

[[NSUserDefaults standardUserDefaults] setValue:testArray forKey:@"testArray"];
[[NSUserDefaults standardUserDefaults] synchronize];

//view controller 2
NSMutableArray *arr = [[NSUserDefaults standardUserDefaults] valueForKey:@"testArray"];

或者我想知道如何将一个视图控制器中的图像保存或传递给另一个视图控制器。

1 个答案:

答案 0 :(得分:2)

您应该将图像保存在文档目录

 - (IBAction)saveImage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
    UIImage *image = imageView.image;
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:savedImagePath atomically:NO];   
}

在另一个ViewController中获取图片

  - (IBAction)getImage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
    UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}

删除图片

     - (void)removeImage
    {
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

      NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
     BOOL success = [fileManager removeItemAtPath:filePath error:&error];
      if (success) {
          UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:@"Congratulation:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
          [removeSuccessFulAlert show];
[imageview removeFromSuperview];
      }
      else
      {
          NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
      }
    }