You can use the predicateWithBlock: approach suggested by @lxt, or you can use the FUNCTION approach. This will result in a predicate that looks like this:
[NSPredicate predicateWithFormat:@"FUNCTION(SELF, 'mySuperMethod:', %@)", aParameter];
If you use this predicate to filter an array, then:
SELF will iteratively be each element in the array- each element of the array will have the
-mySuperMethod: method called -mySuperMethod: will get aParameter as a method parameter-mySuperMethod: will return the BOOL value placed in the NSNumber field <this is very important- all objects that return
YES from -mySuperMethod: will be included in the filtered array.
For more information about this syntax, check out this blog post .
So why can you use this approach for a block approach? I can think of two reasons:
- backward compatibility
- If you need this to work on Leopard (Mac blocks were introduced in Snow Leopard).
- If you need it to work with iOS up to 4.0 (blocks in iOS were introduced in iOS 4.0).
- You want to serialize the predicate for archiving and subsequent retrieval. This is normal if
aParameter conforms to the <NSCoding> protocol. Blocks cannot be serialized.
However, if none of them is a requirement, then the block approach is likely to be better in the long run, as it will become more obvious and readable. :)
source share