ios - 将图像设置为核心数据

标签 ios swift core-data

我有一个加载的 tableviewcells 列表。在每个单元格旁边都有一个“添加到收藏夹”按钮。单击“添加到收藏夹”时,其上的图像将发生变化,并且更改后的图像应存储到 coredata 中,以便再次运行该应用程序时我可以知道哪个单元格被收藏了。为此,这就是已经尝试过的...

        func favoriteBtnTapped(cell: HistoryTableViewCell) {

            if segmentControl.selectedSegmentIndex == 2 {
                favBtnTapFlag = true
                if let indexPath = tableview?.indexPath(for: cell) {

                    let myFavMsg = messages1[indexPath.row]
                    let likedMsg = myFavMsg.historyData


                    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                        return
                    }
                    let managedContext = appDelegate.persistentContainer.viewContext

                    let entity = NSEntityDescription.entity(forEntityName: "FavoritedMessages", in: managedContext)

                    let category = NSManagedObject(entity: entity!, insertInto: managedContext)

                    category.setValue(likedMsg, forKeyPath: "favData")


//New image is set on the cell and it is saved to coredata here...                    
                    cell.favoriteButton.setImage(UIImage(named: "pin"), for: .normal)
    let imageData = UIImageJPEGRepresentation((cell.favoriteButton.imageView?.image)!, 1)

                    category.setValue(imageData, forKey: "favImage")
                    do {

                        try managedContext.save()
                      self.favMessages.append(category as! FavoritedMessages)


                    } catch let error as NSError {
                        print("Could not save. \(error), \(error.userInfo)")
                    }
                }
            }

它是在 viewWillAppear 中获取的,就像这样...

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Messages")

    let fetchRequest1 = NSFetchRequest<NSManagedObject>(entityName: "FavoritedMessages")

    do {
        messages1 = try managedContext.fetch(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) as! [Messages]

        favMessages = try managedContext.fetch(fetchRequest1 as! NSFetchRequest<NSFetchRequestResult>) as! [FavoritedMessages]

        for result in favMessages as [FavoritedMessages] {

            if let imageData = result.value(forKey: "favImage") as? NSData {
                if let image = UIImage(data:imageData as Data) as? UIImage {
                   favoritedImage.image = image 

                }
            }
        }

        tableview.reloadData()
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
   }}

此处 favoritedImage.image = image 我试图将获取的图像分配给 imageview 变量,然后在 cellForRow 处分配它。但我不确定如何做到这一点......

最佳答案

您不应该将图像保存在 coredata 中。

将 favourite_status 为 1 的模型保存在 coredata 中(0 => unfavoured and 1 => favorite )。 (基本上是 bool 值) 根据 favourite_status 从 app bundle 加载图像。

加载单元格时也使用 favourite_status 加载图像。

///已编辑

func favoriteBtnTapped(cell: HistoryTableViewCell) {

     //1. Get Entity from datasource(Array) using indexpath.row
     //2. Favorite the entity by setting favaorite_status = 1  
     //3. Save to coredata also
     //4. Reload Table view 

}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     //1. Get Entity from datasource(Array) using indexpath= Array
     //2. Set cell image based on favaorite_status. Use UIImage.init(name:””) (if favaorite_status  == 0, imagename will be different)

}

关于ios - 将图像设置为核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47751493/

相关文章:

iOS( swift ): representing scaled value as UIColor

iOS 我应该使用 Core Data 吗?

macos - NSXMLStoreType 或 NSSqliteStoreType

iphone - NSOperation 和 NSInvocationOperation 之间的区别?

ios - Xcode 布局约束 : selecting divisions

ios - 如何在没有 GPUImageFilterGroup 的情况下使用 GPUImageLookupFilter?

ios - 在 Swift 中将 Alamofire 调用包装到自定义对象中?

swift - 'UIImagePickerController' 和 'allowsEditing' 在编辑 View 中隐藏这些行

ios - 保存到核心数据时应用程序会卡住几秒钟

ios - 列出所有应用程序并跟踪互联网使用情况