公共云数据库查询不应该返回 nil

Posted

技术标签:

【中文标题】公共云数据库查询不应该返回 nil【英文标题】:Public cloud database query doesn't return nil when it should 【发布时间】:2020-10-07 01:48:28 【问题描述】:

我想检查是否存在带有某个谓词的记录,如果不存在,则执行以下操作:

let publicDatabase = CKContainer.default().publicCloudDatabase
let predicate: NSPredicate!
predicate = NSPredicate(format: "username == %@", usernameText)
let query =  CKQuery(recordType: "user", predicate: predicate)
let configuration = CKQueryOperation.Configuration()
configuration.allowsCellularAccess = true
configuration.qualityOfService = .userInitiated

let queryOperation = CKQueryOperation(query: query)
queryOperation.desiredKeys = ["username"]
queryOperation.queuePriority = .veryHigh
queryOperation.configuration = configuration
queryOperation.resultsLimit = 1
queryOperation.recordFetchedBlock =  (record: CKRecord?) -> Void in
    if let record = record 
    // #1
        print("record \(record)")
     else 
    // #2
        print("none exists")
    


queryOperation.queryCompletionBlock =  (cursor: CKQueryOperation.Cursor?, error: Error?) -> Void in
    if let error = error 
        print("\(error)")
        return
    
    
    if let cursor = cursor 
        print("cursor: \(cursor)")
    


publicDatabase.add(queryOperation)

当存在与谓词匹配的记录时,该记录会按应有的方式返回,但当它不存在时,甚至不会返回 nil 让我做出相应的反应。我的意思是理想情况下我想在 #2 中执行我的代码以响应不存在任何记录,但 recordFetchedBlock 在这种情况下似乎不会运行。

【问题讨论】:

【参考方案1】:

这里的问题是 recordFetchedBlock 仅在您获得记录时才被调用。无记录?然后它不会被调用。以下方法应该可以为您解决问题:

//define an array to store all records
var allRecords = []

queryOperation.recordFetchedBlock =  record in
    //called once for each record
    //if no results, then it is never called
    //if you get a record, add to the array
    allRecords.append[record]


//the query completion block is called at the end of the query (or when all results can't be returned in one block, then called with non-nil cursor value.  Considering that out of scope for this answer.
queryOperation.queryCompletionBlock =  (cursor: CKQueryOperation.Cursor?, error: Error?) in
    if let error = error 
        //handle error
    
    if let cursor = cursor 
       //handle cursor if exists    
     
    if allRecords.count == 0 
        //my query returned no results
        //take desired action    
    

【讨论】:

以上是关于公共云数据库查询不应该返回 nil的主要内容,如果未能解决你的问题,请参考以下文章

核心数据查询值“不是零”不返回值等于 0 的对象

Parse-Server 云代码查询不返回所有列

即使 sql 查询不应该返回任何记录,JUnit 测试仍然通过

核心数据查询,每年最近的汽车?

设置一对多关系后,NSFetchRequest 查询返回 nil

iPhone 歌曲库查询,已知持久标识符返回 nil