核心数据提取请求错误

时间:2019-06-25 05:47:55

标签: ios swift core-data

我有一个正在使用Core Data构建的应用程序。我使用Biking对所有Fetched Results Controller结构进行了初始加载。然后,我尝试仅使用发送请求发送一个请求以检查特定的Biking结构,但是在谓词行上收到错误:Thread 1: EXC_BAD_ACCESS。我只需要此请求即可检查是否保存了具有特定ID的结构。我是这一切的新手,所以请原谅我的无知!我在做什么错了?

private let appDelegate = UIApplication.shared.delegate as! AppDelegate
private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var fetchedRC: NSFetchedResultsController<Biking>!

private func refresh() {
    do {
        let request = Biking.fetchRequest() as NSFetchRequest<Biking>
        if query.isEmpty {
            request.predicate = NSPredicate(format: "bikingOwner == %@", note)

            let sort = NSSortDescriptor(key: #keyPath(Biking.buttonText), ascending: true)
            request.sortDescriptors = [sort]
            do {
                fetchedRC = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
                fetchedRC.delegate = self
                try fetchedRC.performFetch()
            } catch let error as NSError {
                print("Could not fetch. \(error), \(error.userInfo)")
            }
        }
    }
}

var bikingQuery = [Biking]()

var query = "test"

let fetchRequest = Biking.fetchRequest() as NSFetchRequest<Biking>
// ERROR Below
fetchRequest.predicate = NSPredicate(format: "buttonID == %@", query)
do {
    bikingQuery = try context.fetch(fetchRequest)
} catch {
    fatalError("Failed to fetch: \(error)")
}

if bikingQuery.count >= 0 {
    print("Found!")
}

1 个答案:

答案 0 :(得分:0)

替换谓词行

 let query = "test"
 fetchRequest.predicate = NSPredicate(format: "buttonID == %@", query)`

使用

let query:Double = 2.0 // Any Value you want to search

fetchRequest.predicate = NSPredicate(format: "buttonID == %f", query)

有关更多信息,请参见此链接

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

希望对您有帮助