Timm Kent Timm Kent - 1 month ago 13
Swift Question

Using Predicates on Array Objects in Swift returns Error

When I do this... I get a *** NSForwarding: warning: object 0x78ed21a0 of class 'Plantivo1_6.Seed' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[Plantivo1_6.Seed valueForKey:]


If i remember correctly this would work with objective-C. What's my mistake?

let names = ["Tom","Mike","Marc"]
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", "om")
let array = (names as NSArray).filteredArrayUsingPredicate(searchPredicate)

let mySeed1 = Seed() // Seed is just a class that contains a "culture" Property of String
let mySeed2 = Seed()
let mySeed3 = Seed()
mySeed1.culture = "Tom"
mySeed2.culture = "Mike"
mySeed3.culture = "Marc"

let mySeeds = [mySeed1,mySeed2,mySeed3]
let searchPredicate1 = NSPredicate(format: "SELF.culture CONTAINS[c] %@", "om")
let array1 = (mySeeds as NSArray).filteredArrayUsingPredicate(searchPredicate1)


Does your Seed class inherit from NSObject?

If not, this is the message you will get.


class Seed: NSObject {

Edit: stklieme is correct - to use NSPredicate, your object's class needs to implement -valueForKey as defined by the NSKeyValueCoding protocol. You can either define your own implementation of -valueForKey, or just make your class inherit from NSObject which takes care of that for you.

This is defined in the Apple docs for NSPredicate,

You can use predicates with any class of object, but the class must support key-value coding for the keys you want to use in a predicate.