问题描述
我的当前代码如下:
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"))
}
}
上面的代码抛出了如下异常(NSUnknownKeyException
):
The above code throws throws the following Exception (NSUnknownKeyException
):
对象类型 '[valueForUndefinedKey:]
':
此类不符合键 userId
的键值编码.
Apple 的 filter(using:)
文档没有指定任何可能导致此问题的更改.
The document of Apple for filter(using:)
does not specify any changes that could be causing this issue.
如何在 Swift 4.0 中使用 NSPredicate
?
How can I use NSPredicate
in Swift 4.0?
此外,根据要求,我尝试使用 @objc
.但是,还是一样的错误.
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
}
}
收到针对此问题的进一步评论后,将 @objc 属性添加到 userId
时,我收到以下消息.属性不能被标记@objc,因为它的类型不能在Objective-C中表示
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 属性 NSPredicate 它完全可以正常工作.- 将@objc 添加到类- 另外,将@objc 添加到属性
String property NSPredicate it works completely fine.- Add @objc to class- Also, add @objc to property
推荐答案
为什么不直接使用 filter
?它更像是Swift-y",不涉及将数组转换为 NSArray
.
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 }
这篇关于NSPredicate NSUnknownKeyException - Swift 4.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!