一些iOS照片相关应用程序会将使用该应用程序创建的图像存储在照片库之外的其他位置.例如,Fat Booth显示了应用启动时使用该应用创建的照片滚动列表.注意:这些照片是持久化的,用户不需要将其显式保存到照片库中.What is the simplest way to save and persist images inside an iOS application?

我所熟悉的唯一持久性store 是NSUserDefaults和key chain.然而,我从来没有听说过这些用来存储更大的数据块,比如图像.现在我想知道核心数据是否是最简单的方法.

推荐答案

使用最简单的路径保存应用程序中的文档:

NSData *imageData = UIImagePNGRepresentation(newImage);

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

NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];

NSLog(@"pre writing to file");
if (![imageData writeToFile:imagePath atomically:NO]) 
{
    NSLog(@"Failed to cache image data to disk");
}
else
{
    NSLog(@"the cachedImagedPath is %@",imagePath); 
}

然后将imagePath保存在NSUserDefaults中的某个字典中,或者以您喜欢的方式保存,然后要检索它,只需执行以下操作:

 NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];

Objective-c相关问答推荐

将 NSArray 保存到 NSUserDefaults 并在 NSMutableArray 中获取它

'if not' 的 Objective-C 预处理器指令

iOS 块和对自身的强/弱引用

测试应用程序是否确实从 UILocalNotification 变为活动状态

更改 UINavigationBar 字体属性?

当我从导航控制器推送时如何隐藏导航栏?

[Facebook-iOS-SDK 4.0]如何从FBSDKProfile获取用户邮箱

在 Xcode 中打破 EXC_BAD_ACCESS?

如何在 iPhone 上默认显示数字键盘?

如何在 iPhone 中将 NSData 转换为字节数组?

在Objective-C中替换字符串中的一个字符

将块存储在数组中

在 Objective C 中,你能判断一个对象是否具有特定的属性或消息吗?

如何将 nil 添加到 nsmutablearray?

NSCharacterSet:如何将_添加到 alphanumericCharacterSet 文本限制?

遍历 NSString 中所有字符的最有效方法

嵌入自定义容器视图控制器时,内容位于导航栏下方.

获取最顶层的 UIViewController

分组的 UITableView 在底部有 20px 的额外填充

Block 隐式保留'self';明确提及touch以表明这是预期行为