ios - 如何修复 "' NSInvalidArgumentException',原因: '-[__NSCFNumber caseInsensitiveCompare:]: unrecognised selector sent to instance"?

标签 ios swift core-data ios13

我正在创建一个新应用程序,需要帮助让我的核心数据实体在单击相应的 tableView 单元格时更新字段。

我尝试过用谷歌搜索错误和类似的错误,但我能找到的所有内容都是在 Objective-c 或旧版本的 swift 中。我正在使用 swift 。我还使用 NSFetchedResultsController 来获取数据。

这是我的tableView的selectRowAt

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let item = fetchedRC.object(at:indexPath)

    /*if item.isComplete {
        item.setValue(false, forKey: "isComplete")
        //item.isComplete = false
    } else {
        item.setValue(true, forKey: "isComplete")
        //item.isComplete = true
    }*/

    item.isComplete.toggle()

    do {
        try context.save()
        tableView.reloadRows(at: [indexPath], with: .automatic)
    } catch let error as NSError {
        print("Could not save. \(error.localizedDescription)")
    }
}

当用户单击单元格时,我希望 IsComplete 根据 true 或 false 切换其值。但实际上,当在 if 语句的两种情况下调用“setValue”时,它实际上会崩溃。错误信息是:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber caseInsensitiveCompare:]: unrecognised selector sent to instance 0x9321d02e963b75fc'

编辑: 我相信这就是 isComplete 声明的地方

extension Item {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
        return NSFetchRequest<Item>(entityName: "Item")
    }

    @NSManaged public var name: String?
    @NSManaged public var isComplete: Bool
    @NSManaged public var list: List?

}

还有 DidSet:

var detailedList: List! {
    didSet {

   }
}

请求和排序

let request = Item.fetchRequest() as NSFetchRequest<Item>
    request.predicate = NSPredicate(format: "list = %@", parentObj)
    let sort = NSSortDescriptor(key: #keyPath(Item.isComplete), ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
    request.sortDescriptors = [sort]
    do {
        fetchedRC = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        try fetchedRC.performFetch()
        self.tableView.reloadData()
    } catch let error as NSError{
        print(error.localizedDescription)
    }
    fetchedRC.delegate = self

最佳答案

发生错误的原因是您无法使用 caseInsensitiveCompare 选择器对 Bool 值进行排序。

只需使用标准描述符

let sort = NSSortDescriptor(key: #keyPath(Item.isComplete), ascending: true)

关于ios - 如何修复 "' NSInvalidArgumentException',原因: '-[__NSCFNumber caseInsensitiveCompare:]: unrecognised selector sent to instance"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495296/

相关文章:

swift - 表格 View 单元格中的按钮导致不必要的滚动

ios - 具有一对多关系的 NSPredicate

ios - 如何获取数组中项目的索引?

ios - UIView 子类不能使用 UIView 自定义类?

ios - 为 iOS 应用程序存储数据的最佳方法?

Swift 4 - 核心数据为 UIPickerView 获取不同的值

ios - 在数据库中为重复事件建模,并使用UILocalNotification触发事件

ios - setUp() 方法在调用每个测试方法之前是如何调用的?

ios - 有关 crashlytics 的步骤

iphone - NSDictionary中NSArray的NSPredicate