Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform an NSArray filteredArrayUsingPredicate where the predicate is a method?

How can I perform an NSArray filteredArrayUsingPredicate where the predicate is a method? That is what would a simple code example look like here?

I've been trying to go through the predicate doco and getting a little confused. I can see how it works for simple checks, but if I have a check which requires a few lines of objective-c code to implement what would the code look like to effectively:

  • filter an NSArray using filteredArrayUsingPredicate
  • predicate would be a method which somehow takes an input variable(s), performs whatever checks and balances and then gives a TRUE/FALSE back as a return value re whether the item should be filtered or not

thanks

like image 716
Greg Avatar asked Dec 13 '22 15:12

Greg


1 Answers

As long as you're going with iOS 4.0 and above you'll be glad to know this is really straightforward (the following isn't available on 3.x).

You can use the predicateWithBlock method to create a NSPredicate that takes a block that returns YES or NO as its argument. So pretty much exactly what you want (if you're not familiar with blocks they're basically a way to encapsulate a method. See here: http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1)

+ (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block

like image 152
lxt Avatar answered Feb 06 '23 00:02

lxt