How can I execute NSArray filterArrayUsingPredicate where the predicate is a method?

How can I execute NSArray filterArrayUsingPredicate where the predicate is a method? Here's what a simple code example looks like here?

I am trying to pass the predicate doco and get a little confused. I can see how this works for simple checks, but if I have a check that requires several lines of objective-c code to implement how the code would look efficient:

  • filter NSArray using filterArrayUsingPredicate Predicate
  • would be a method that somehow accepts the input variable (s), performs any checks and balances, and then returns TRUE / FALSE as the return value again, whether the element should be filtered or not

thanks

+4
source share
2 answers

As long as you go with iOS 4.0 and above, you will be glad to know that it is very simple (at 3.x).

You can use the predicateWithBlock method to create an NSPredicate that takes a block that returns YES or NO as an argument. Thus, pretty much exactly what you want (if you are not familiar with blocks, this is basically a method of encapsulating a method. See here: http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks -1 )

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

+7
source

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. :)

+6
source

Source: https://habr.com/ru/post/1344439/


All Articles