NSPredicate: how to do NOT EndsWith?

I have a list of images in the application set and I need to display the corresponding ones in the application, the image has the format:

###_photo_#.jpg ###: toy id, from 1000 to 2000 #: photo id, from 1 

eg,

 1000_photo_1.jpg 1000_photo_2.jpg 

I used to get the list of files in the bundle and used the predicate to filter other files:

 @"self ENDSWITH '.jpg' AND self BEGINSWITH '%d_photo_'", toyId 

but now there are retinal images that end with @ 2x.jpg, so this method needs to be fixed, I’m thinking about adding:

 NOT ENDSWITH '@2x.jpg' 

but is this true? I have to say:

 NOT (ENDSWITH '@2x.jpg') 

or

 (NOT ENDSWITH '@2x.jpg') 

instead

+6
source share
4 answers

I think the best option in iOS 4.0+ is to use NSPredicate predicateWithBlock: to determine your conditions. This way you can use standard NSString functions like hasSuffix: to check your ends with a negative case.

Check out the good tutorial here: http://www.wannabegeek.com/?p=149

Here is the basic way to use it.

 NSInteger toyId = 10; NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { return [evaluatedObject hasSuffix:@".jpg"] && ![evaluatedObject hasSuffix:@"@2x.jpg"] && [evaluatedObject hasPrefix:[NSString stringWithFormat:@"%@_photo_", [NSNumber numberWithInt:toyId]]]; }]; 

Then you can capture an array of files

 [arrayOfFiles filterArrayUsingPredicate:predicate]; 
+1
source

You can use the predicate string as follows:

 @"(self ENDSWITH '.jpg') AND NOT (self ENDSWITH '@2x.jpg') AND (self BEGINSWITH '%d_photo_')" 
+8
source

You can encapsulate a predicate in another predicate:

 NSPredicate *positivePredicate = [NSPredicate ...]; NSPredicate *negativePredicate = [NSCompoundPredicate notPredicateWithSubpredicate: positivePredicate]; 

This allows you to save an existing text string. Note that with NSCompoundPredicate you can also create AND and OR predicates. From these three (AND, OR, NOT), you can even get things like XNOR and NAND predicates (although how to do this, the exercise is left to the reader ...)

+5
source

Try the following:

 NOT something ENDSWITH '@2x.jpg' 
+1
source

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


All Articles