ios - swift - NSPredicate 和 Context Save 运行不正常

标签 ios iphone swift nspredicate

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

   @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

}

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

最佳答案

如果你想检查声音是否在收藏夹中,如果不添加新声音你必须改变步骤的顺序

@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)。

关于ios - swift - NSPredicate 和 Context Save 运行不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44746151/

相关文章:

ios - Swift - API 调用/CompletionHandler/URLSession 出现问题

ios - 我如何快速更新其他 Controller 的用户界面?

ios - 如何从堆栈中删除旧的 ViewController

ios - 一起识别长按和平移手势识别器

cocoa-touch - 如何在我的应用程序中共享 CLLocation?

iphone - Game Center localPlayer 始终经过身份验证

iphone - 将 GPS 集成到我的应用程序中

iphone - 检测 iOS 的同步事件

ios - 添加 Google map 作为 subview 无限调用 viewDidLoad()

ios - SQLite DB - 执行结果是什么意思?