如果你想使用 Core Data,我认为保存图像数组最简单的方法是在添加新图像或删除图像时保存它们。
Core Data 数据模型非常简单。您可以只添加一个名为 Image 的实体或任何在您的上下文中有意义的实体。向实体添加 image 属性。将属性的类型设置为“数据”。生成NSManagedObject 子类,模型就完成了。
现在,您需要如何以及何时保存图像?我认为您应该仅在用户创建新图像时将图像插入核心数据上下文。当用户删除图像时,您应该从 Core Data 上下文中删除一个对象。因为如果用户在您的应用会话中没有对图像执行任何操作,则无需再次保存图像。
要保存新图像,
// 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)
}
我想你知道如何从 Core Data 中删除图像,对吧?
当需要显示图像的 VC 出现时,您执行 NSFetchRequest 并获取所有保存为 [AnyObject] 的图像并将每个元素转换为 Image。然后,使用init(data:) 初始化器将数据转换为UIImages。
编辑:
这里我将向您展示如何将图像恢复为[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.
}