我正在努力找出NSPredicate。下面的课程是由数据组成的。我正在尝试搜索一组对象。在一个对象中,我想搜索一个字符串数组的属性:favoriteTeams。
class Person: NSObject {
let firstName: String
let nicknames: [String]
let favoriteTeams: [String]
init(firstName: String, nicknames: [String], favoriteTeams: [String]) {
self.firstName = firstName
self.nicknames = nicknames
self.favoriteTeams = favoriteTeams
}
}
let robert = Person(firstName: "Robert", nicknames: ["Bob", "Robbie"], favoriteTeams: ["Patriots", "Bruins", "Celtics"])
let tim = Person(firstName: "Timothy", nicknames: ["Timmy", "Tim", "Timbo"], favoriteTeams: ["Patriots", "Montreal", "Celtics"])
let william = Person(firstName: "William", nicknames: ["Will", "Willie", "Bill"], favoriteTeams: ["Jets", "MapleLeafs", "Lakers"])
let stephen = Person(firstName: "Stephan", nicknames: ["Steve", "Stevie"], favoriteTeams: ["Patriots", "Bruins", "Lakers"])
let people = [robert, tim, william, stephen]
let searchTeam = "Patriots"
let robertPredicate = NSPredicate(format: "firstName = 'Robert'")
let teamPredicate = NSPredicate(format: "favoriteTeams CONTAINS[c] %@", searchTeam)
(people as NSArray).filtered(using: robertPredicate)
后者返回对象罗伯特。
(people as NSArray).filtered(using: teamPredicate)
更正了缺少的“NSPredicate”。但是,后者返回看似空数组的内容。