【问题标题】:how to update the image in table view cell using core data如何使用核心数据更新表格视图单元格中的图像
【发布时间】:2016-08-11 13:26:12
【问题描述】:

我正在使用图像选择器从本地设备库中选择图像,但是一旦使用 xcode 7.3、ios9 和 swift 2.2 使用核心数据关闭库后,图像就不会保存并显示在表格视图单元格中

 if isUpdate == true{
            print("object id \(self.store?.objectID)")
            self.store?.sName = name.text
            self.store?.sDescription = desc.text
            //save.setTitle("my text here", forState: .Normal)
            let img = UIImage(named: "image.jpeg")
            let imgData = UIImageJPEGRepresentation(img!,1)
            self.store?.sImage = imgData
            do {
                try appdelegate.managedObjectContext.save()
                self.navigationController?.popViewControllerAnimated(true)
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            }

        }else{
            //get the description of the entity
            let storeDescription = NSEntityDescription.entityForName("Store",inManagedObjectContext: appdelegate.managedObjectContext)

            //we create managed object to be inserted to core data
            let store = EventsandnotesStore(entity : storeDescription!,insertIntoManagedObjectContext:appdelegate.managedObjectContext)
            store.sName = name.text
            store.sDescription = desc.text
            //
            let img = UIImage(named: "image.jpeg")

            let imgData = UIImageJPEGRepresentation(img!,1)

            store.sImage = imgData
            do {
                try appdelegate.managedObjectContext.save()
                self.navigationController?.popViewControllerAnimated(true)
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            }

          }


    }

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    由于您没有提到名称和描述字段或商店对象的创建问题,我假设一切正常,并且您对 CoreData 流程没问题。

    要检查的一件事是 JPEG 转换调用中的整数值 1。那应该是一个浮点数,所以在调用中尝试 1.0,尽管我很惊讶没有被 XCode 捕获。不确定这是否会导致您的问题。

    我遇到的转换可能遇到的另一个潜在问题是 UIImageJPEGRepresentation 调用可能由于其他原因而失败,返回一个 nil 值(例如,当我将 CIImage 直接转换为 UIImage 时发生这种情况,但如果我通过 CGImage 做到这一点,它就会起作用 - 去图)。鉴于所有这些,您应该检查调用的结果。我使用如下守卫语句和自定义记录器:

        guard let thumbnailData = UIImageJPEGRepresentation(thumbnailUI, Set.shared.jpegQuality) else
        {
            logError(#file, line: #line, column: #column, function: #function, description: "JPG Conversion Error - thumbnail")
            return nil
        }
    

    如果失败,您需要检查从选择器获取的图像。

    如果您在数据库方面遇到问题,您是否在视图控制器中包含了 TableView 委托函数(controllerWillChangeContent 等)。您将需要这些,以便在图像记录发生更改时调用您的 configureCell 方法。

    这些是我要开始的事情。

    【讨论】:

    • 我不小心给不同的图片起了相同的名字,用logError修复了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2021-10-10
    • 2011-09-16
    相关资源
    最近更新 更多