我有一个 UIImages
数组,它是动态的。
所以用户可以将照片添加到这个数组中。
我的问题是我怎样才能保存这个数组,因为我尝试了一些东西,但它们似乎都不适合我。
我欢迎提出如何完成这项任务的建议。
谢谢。
最佳答案
如果你想使用 Core Data,我认为保存图像数组的最简单方法是在添加新图像或删除图像时保存它们。
Core Data 数据模型非常简单。您可以只添加一个名为 Image
的实体或任何在您的上下文中有意义的实体。向实体添加 image
属性。将属性的类型设置为“数据”。生成 NSManagedObject
子类,模型就完成了。
现在,您需要如何以及何时保存图像?我认为您应该仅在用户创建新图像时才将图像插入核心数据上下文。当用户删除图像时,您应该从 Core Data 上下文中删除一个对象。因为如果用户在您的应用 session 中对图像不执行任何操作,则无需再次保存图像。
要保存新图像,
// 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]
的图像并将每个元素转换为 图像
。然后,使用 init(data:)
初始化程序将数据转换为 UIImage
。
编辑:
在这里,我将向您展示如何将图像返回为 [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.
}
关于ios - 如何在 xCode 中保存一组 UIimages (swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779296/