我有一个检查核心数据的功能。如果不存在,它应该写入其中(但它不是那样工作的)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/