NSPredicate对象模型数组过滤器在Swift 4.0中无法正常运行

时间:2018-02-20 08:57:10

标签: ios swift xcode filter nspredicate

  1. 我在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)
    

2 个答案:

答案 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)

  1. var是针对Mutable Content / Variables
  2. 引入的
  3. 在swift中,您可以使用filter替代NSPredicate
  4. 尝试这样:

                //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)