swift - NSPredicate 和 Context Save 运行不正常

swift - NSPredicate and Context Save is not working well

我有检查核心数据的功能。如果不存在,它应该写入其中(但它不是那样工作的)SoundItems 是一个包含收藏夹 objects 的数组,mainArray 是包含真实 objects;[=13= 的数组]

   @IBAction func Favori(_ sender: Any) {
        // save core data
        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        let newSound = NSEntityDescription.entity(forEntityName: "Sounds", in: context)
        let sound = NSManagedObject(entity: newSound!, insertInto: context)
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Sounds")

        let predicate = NSPredicate(format: "soundName = %@", soundArray[soundIndex].deletingPathExtension().lastPathComponent)
        fetchRequest.predicate = predicate
        do {
         let fetchResults = try context.fetch(fetchRequest) as? [Sounds]
              if fetchResults!.count > 0 {

                print("already favd")
            }
         else {

               sound.setValue(soundArray[soundIndex].deletingPathExtension().lastPathComponent, forKey: "soundName")
                    try context.save()
                        soundItems.append(sound)
                            print(sound)

            }
        }

        catch {
        print(error)
        }
    }

这里是列出核心数据的代码;

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
    let sound = soundItems[indexPath.row]
    cell.textLabel?.text = sound.value(forKey: "soundName") as? String

    return cell

}

我尝试 运行 调试模式下的代码,当没有重复的核心数据并添加到 tableView 列表中时它工作正常。 但情况是这样的;当核心数据存在时(fetchResults!.count > 0)仍然在表视图中添加为 nil label.text 但总是添加 mainArray[0]

的项目

@vadian 说的对。为什么在获取数据之前插入新声音?

 let newSound = NSEntityDescription.entity(forEntityName: "Sounds", in: context)
 let sound = NSManagedObject(entity: newSound!, insertInto: context)

如果您想检查声音是否在收藏夹中,如果没有添加新声音,则必须更改步骤顺序

@IBAction func Favori(_ sender: Any) {
    // save core data
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    let fetchRequest : NSFetchRequest<Sounds> = Sounds.fetchRequest()
    let favName = soundArray[soundIndex].deletingPathExtension().lastPathComponent
    let predicate = NSPredicate(format: "soundName = %@", favName)
    fetchRequest.predicate = predicate
    do {
        let fetchResults = try context.fetch(fetchRequest)
        if fetchResults.isEmpty {
            let newSound = NSEntityDescription.insertNewObject(forEntityName: "Sounds", into:context) as! Sounds
            newSound.soundName = favName
            try context.save()
            soundItems.append(newSound)
            print(newSound)
        }
        else {
             print("already favd")
        }
    }

    catch {
        print(error)
    }
}

建议以单数形式命名实体(Sound)。