if else语句定义NSPredicate

时间:2017-06-04 00:57:47

标签: ios swift nspredicate

我正在尝试基于段控制器开关定义谓词。

if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@" , predicatearray)
} else if self.streamtype == "case2" {
    let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)

我收到错误说:

  

"无法发送到NSPredicate类的抽象对象:创建一个具体的实例!"

另外,它告诉我从未使用过谓词变量的初始化。我尝试用几种不同的方式编写函数,但这对我来说最有意义,因为我只需要在加载新信息时更新谓词,所以我只将两个函数放在一起。

1 个答案:

答案 0 :(得分:2)

您在if {}else {}范围内定义谓词,这就是为什么它在范围之外不可见。

var predicate : NSPredicate!
if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
} else if self.streamtype == "case2" {
    predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)