仅获取cloudkit中的特定字段?

时间:2017-02-22 18:54:00

标签: ios swift field cloudkit

我想在CloudKit中的Musics记录中仅获取Song_Name字段。我正在尝试下面的代码,但它仍然取得音乐记录中的所有字段。我想我需要使用publicDB.add(operation)方法编译操作,但它不允许我像现在一样使用publicDB.perform(query,in ....)声明“结果”

 let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Musics", predicate: predicate)
    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["Song_Name"]

    publicDB.perform(query, inZoneWith: nil) { [unowned self] results, error in

        guard error == nil else {
            DispatchQueue.main.async {
                self.delegate?.errorUpdating(error! as NSError)
                print("Cloud Query Error - Refresh: \(error)")
            }
            return
        }
        self.items_music.removeAll(keepingCapacity: true)
        for record in results! {
            let music = Musics(record: record, database: self.publicDB)
            self.items_music.append(music)
        }
        DispatchQueue.main.async {
            self.delegate?.modelUpdated()
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您正在创建CKQueryOperation并设置操作的desiredKeys属性,但之后您没有使用此操作。您只需对数据库执行查询,因此不会使用任何查询操作的属性。

您需要为操作分配记录提取的块和查询完成块,然后将操作添加到数据库以实际运行它。

let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Musics", predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["Song_Name"]
var newItems = [Musics]()
operation.queryCompletionBlock = ( { (cursor, error)->Void in
    guard error == nil else {

        DispatchQueue.main.async {
            self.delegate?.errorUpdating(error! as NSError)
            print("Cloud Query Error - Refresh: \(error)")
        }
        return
    }
    self.items_music = newItems
    DispatchQueue.main.async {
        self.delegate?.modelUpdated()
    }
})

operation.recordFetchedBlock = ( { (record) -> Void in
    let music = Musics(record: record, database: self.publicDB)
    newItems.append(music)
})

publicDB.add(operation)

我省略了一些您需要的代码,用于检查提供给完成块的cursor。如果这不是nil,那么您需要发出另一个查询来获取其他项