ios - 如何在 xCode 中保存一组 UIimages (swift)

标签 ios swift uiimage save

我有一个 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/

相关文章:

ios 8 自定义键盘 UIViewServiceInterfaceErrorDomain?

xcode - MacOS swiftui NSLayoutConstraint 调整错误对象的大小

ios - 如何从 RAM 内存中清除图像

iphone - 在加载 View 中创建 View 并设置它的框架,但框架自动更改

ios - 无法使用 Int.random(in : x. ..y) 在 Swift 中随机化数组

ios - 当我创建 NSManagedObject 的子类时,我得到 'failed code with exit 1'

swift - 在 Swift 中从自定义相机拍摄后裁剪图像

ios - scrollRectToVisible:CGRectMake无法正常工作

ios - 如何将 AppClip 添加到 Siri 的附近建议?

ios - 如何使用 swift 将图像从 Images.xcassets 加载到 UIImage