我在swift 4.0中工作,我在MutableArray中有模型对象, NSPredicate无法正常工作。
//Here is code
//Model class:
class Modelclass: NSObject
{
var firstName:String!
var lastName:String!
}
// Viewcontroller doing predicate:
let ary = NSMutableArray()
let userModel = Modelclass()
userModel.firstName = "Arrya"
userModel.lastName = "stark"
ary.add(userModel)
let commitPredicate = NSPredicate(format: "firstName == %@", "Arrya")
let resultAry = ary.filtered(using: commitPredicate)
print(resultAry)
答案 0 :(得分:2)
我解决了这个问题, 解决方案1:
//I just added below code in model class
extension Modelclass {
@objc override func value(forKey key: String) -> Any? {
switch key {
case "firstName":
return firstName
case "lastName":
return lastName
default:
return nil
}
}
}
解决方案2:
在变量之前添加@objc:
class Modelclass: NSObject
{
@objc var firstName:String!
@objc var lastName:String!
}
答案 1 :(得分:1)
var
是针对Mutable Content / Variables filter
替代NSPredicate
尝试这样:
//Model class:
class Modelclass
{
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
// Viewcontroller doing predicate:
var ary:[Modelclass] = []
let userModel = Modelclass(firstName: "Arrya", lastName: "stark")
ary.append(userModel)
let resultAry = ary.filter{ $0.firstName == "Arrya" }
print(resultAry)