我有一个UIImages
数组,它是动态的。这样用户就可以将照片添加到此数组中。我的问题是如何保存这个数组,因为我尝试了一些方法,但它们似乎都不适用于我。我欢迎如何完成这项任务的建议。
谢谢。
发布于 2016-08-05 09:52:24
如果您想使用Core Data,我认为保存图像数组的最简单方法是在添加新图像或删除图像时保存它们。
核心数据数据模型非常简单。您只需添加一个名为Image
的实体或任何在您的上下文中有意义的实体。向实体添加image
属性。将属性的类型设置为"Data“。生成NSManagedObject
子类,模型就完成了。
现在,您需要如何以及何时保存图像?我认为只有当用户创建新图像时,才应该将图像插入到核心数据上下文中。当用户删除图像时,您应该从核心数据上下文中删除对象。因为如果用户在应用程序的会话中不对图像执行任何操作,就没有必要再次保存图像。
要保存新图像,
// I assume you have already stored the new image that the user added in a UIImage variable named imageThatTheUserAdded
let context = ... // get the core data context here
let entity = NSEntityDescription.entityForName(...) // I think you can do this yourself
let newImage = Image(entity: entity, insertIntoManagedObjectContext: context)
newImage.image = UIImageJPEGRepresentation(imageThatTheUserAdded, 1)
do {
try context.save()
} catch let error as NSError {
print(error)
}
我想你知道如何从核心数据中删除图像,对吧?
当需要显示图像的VC出现时,您可以执行NSFetchRequest
并获取保存为[AnyObject]
的所有图像,并将每个元素强制转换为Image
。然后,使用init(data:)
初始化器将数据转换为UIImage
s。
编辑:
在这里,我将向您展示如何将图像恢复为[UIImage]
let entity = NSEntityDescription.entityForName("Image", inManagedObjectContext: dataContext)
let request = NSFetchRequest()
request.entity = entity
let fetched = try? dataContext.executeFetchRequest(request)
if fetched != nil {
let images = fetched!.map { UIImage(data: ($0 as! Image).image) }
// now "images" is the array of UIImage. use it wisely.
}
https://stackoverflow.com/questions/38779296
复制相似问题