首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >公有云数据库查询本应返回nil,但未返回nil

公有云数据库查询本应返回nil,但未返回nil
EN

Stack Overflow用户
提问于 2020-10-07 09:48:29
回答 1查看 41关注 0票数 0

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

代码语言:javascript
运行
复制
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似乎不会运行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-07 15:46:47

这里的问题是,只有在获得记录时才会调用recordFetchedBlock。没有记录?那么它就不会被调用。下面的方法应该可以帮你解决这个问题:

代码语言:javascript
运行
复制
//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    
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64236075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档