【问题标题】:iPhone UIImage - Data PersistanceiPhone UIImage - 数据持久性
【发布时间】:2009-11-24 09:50:32
【问题描述】:

关于应用程序会话之间数据持久性的简单问题。

我的应用程序允许用户使用 UIImagePickerController 从库中选择图像。然后将所选照片用作应用程序的背景。

由于 UIImagePickerController 委托方法实际上返回的是图像而不是图像路径,我想知道在用户会话中保留该图像的最佳方法是什么?

目前我不需要保留任何其他数据,因为其他所有数据都是从 SQL Server 中提取的,但我不希望将图像也存储在服务器中而增加开销,这意味着每次用户打开应用程序时,首先必须从服务器将背景图像下载到字节数组中,然后再转换为图像。

我找到了以下可以保存图片的代码:

- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//save image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,  YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];

}

我现在不在 Mac 上,所以我无法测试这段代码,但我对上面的代码有几个问题:

我不希望文件系统中出现大量文件。所以我想要一个背景文件(background.png);上面的代码如何处理这个文件已经存在的情况?

它会覆盖现有文件还是会引发错误?

我将如何再次加载图像?

【问题讨论】:

    标签: ios objective-c iphone uiimage persistence


    【解决方案1】:

    你必须先删除文件:

    - (void)saveImage:(UIImage *)image withName:(NSString *)name {
        //save image
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask,  YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
    
        NSError *error = nil;
        if( [fileManager fileExistsAtPath:fullPath] ){
            if( ! [fileManager removeItemAtPath:fullPath error:&error] ) {
                NSLog(@"Failed deleting background image file %@", error);
                // the write below should fail. Add your own flag and check below.
            }
        }
        [data writeToFile:fullPath atomically:YES];
    }
    

    回读应该如下工作:

    ...
    UIImage *bgImage = [UIImage imageWithContentsOfFile:fullPath];
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2012-12-28
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      相关资源
      最近更新 更多