Reputation: 6730
I'm unsure how to write this NSPredicate
to achieve the following. I have an array of prefixes, and I want to know if any of them (plus an underscore) are the prefix of a given string. I don't need to know which matched, just a yes/no if any matched at all.
I can't seem to work this out, at the moment I have this
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSArray *bins = @[@"aaa", @"bbb", @"ccc"];
NSString* item = @"aaa_blah";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ BEGINSWITH SELF", item];
NSLog(@"%@", [[bins filteredArrayUsingPredicate:pred] count] ? @"YES" : @"NO");
}
}
The only way I could think of doing it was filtering the array - so firstly is there a better approach?
And secondly, I want it to return true only if the prefix is followed by an underscore so
@[@"aaa", @"bbb", @"ccc"];
@"aaa_blah"; // YES
@"aaablah"; // NO
@"bbbblah"; // NO
I'm not sure how to do that?
Upvotes: 1
Views: 1224
Reputation: 1885
+(void)checkIfExists:(NSArray *)prefixes inMyobjects:(NSArray *)myObjects withDivider:(NSString *)divider
{
divider = @"_";
prefixes = @[@"aaa",@"bbb",@"ccc"];
myObjects = @[@"aaa_sd",@"dsf_ds",@"aaa_sss",@"aaabbb"];
NSMutableArray * resultsOfPredicate = [NSMutableArray new];
for (NSString * pre in prefixes)
{
NSString * iAmLookingFor = [NSString stringWithFormat:@"%@%@", pre, divider];
NSPredicate *prefixPredicate = [NSPredicate predicateWithFormat:@"SELF beginsWith[c] %@", iAmLookingFor];
NSArray * resultOfSearch = [myObjects copy];
resultOfSearch = [resultOfSearch filteredArrayUsingPredicate:prefixPredicate];
NSLog(@"ros %@",resultOfSearch);
[resultsOfPredicate addObject:@([resultOfSearch count])];
}
for (int i = 0; i<[resultsOfPredicate count]; i++)
{
NSLog(@"prefix %@ isAppeared:%d",[prefixes objectAtIndex:i], [[resultsOfPredicate objectAtIndex:i] boolValue]);
}
}
I hope this will help.
Upvotes: 3