NSPredicate NSUnknownKeyException - Swift 4.0

[亡魂溺海] 提交于 2019-12-12 04:39:13

问题


I have my current code as listed below:

class ViewController:UIViewController{

ovveride func viewDidLoad(){
 filterData()
}

func filterData(){
  var usersArray = [User(name:"John",userId:1),User(name:"Ed",userId:2),User(name:"Ron",userId:3)]

 let filteredData = (userArray as NSArray).filtered(using:NSPredicate(format: "userId=1"))
}
}

The above code throws throws the following Exception (NSUnknownKeyException):

The Object Type '[<ViewController.User 0x6000000afa20> valueForUndefinedKey:]':
this class is not key value coding-compliant for the key userId.

The document of Apple for filter(using:) does not specify any changes that could be causing this issue.

How can I use NSPredicate in Swift 4.0?

Also, as requested, I tried using @objc. But, still the same error.

@objc
class User:NSObject{
 var name:String!
var userId:Int!

init(name:String,userId:Int){
self.name = name
self.userId = userId
}
}

With Further Comments received for this question, on adding @objc attribute to the userId I receive the below message. property cannot be marked @objc because its type cannot be represented in Objective-C

@objc
class User:NSObject{
 @objc var name:String!
var userId:Int! //@objc here results in error 

init(name:String,userId:Int){
self.name = name
self.userId = userId
}
}

String property NSPredicate it works completely fine. - Add @objc to class - Also, add @objc to property


回答1:


Why not just use filter? It's much more "Swift-y" and doesn't involve converting your array to an NSArray.

let filteredData = usersArray.filter { $0.userId == 1 }


来源:https://stackoverflow.com/questions/46864544/nspredicate-nsunknownkeyexception-swift-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!