NSCompoundPredicate - objective-c

I'm trying to filter a UITableView's data using a UISearchDisplayController and NSCompoundPredicate. I have a custom cell with 3 UILabels that I want to all be filtered within the search, hence the NSCompoundPredicate.
// Filter the array using NSPredicate(s)
NSPredicate *predicateName = [NSPredicate predicateWithFormat:#"SELF.productName contains[c] %#", searchText];
NSPredicate *predicateManufacturer = [NSPredicate predicateWithFormat:#"SELF.productManufacturer contains[c] %#", searchText];
NSPredicate *predicateNumber = [NSPredicate predicateWithFormat:#"SELF.numberOfDocuments contains[c] %#",searchText];
// Add the predicates to the NSArray
NSArray *subPredicates = [[NSArray alloc] initWithObjects:predicateName, predicateManufacturer, predicateNumber, nil];
NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
However, when I do this, the compiler warns me:
Incompatible pointer types initializing 'NSCompoundPredicate *_strong'
with an expression of type 'NSPredicate *'
Every example I've seen online does this exact same thing, so I'm confused. The NSCompoundPredicate orPredicateWithSubpredicates: method takes an (NSArray *) in the last parameter, so I'm REALLY confused.
What's wrong?

First of all, using "contains" is very slow, consider mayber "beginswith"?
Second, what you want is:
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
Three, you could've just done something like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.productName beginswith[cd] %# OR SELF.productManufacturer contains[cd] %#", searchText, searchText];

orPredicateWithSubpredicates: is defined to return an NSPredicate*. You should be able to change your last line of code to:
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
... and still have all of the compoundPredicates applied.

Here's an useful method i created based on the answers above (which i thank very much!)
It allows to create an NSPredicate dynamically, by sending an array of filter items and a string which represents the search criteria.
In the original case, the search criteria changes, so it should be an array instead of a string. But it may be helpful anyway
- (NSPredicate *)dynamicPredicate:(NSArray *)array withSearchCriteria:(NSString *)searchCriteria
{
NSArray *subPredicates = [[NSArray alloc] init];
NSMutableArray *subPredicatesAux = [[NSMutableArray alloc] init];
NSPredicate *predicate;
for( int i=0; i<array.count; i++ )
{
predicate = [NSPredicate predicateWithFormat:searchCriteria, array[i]];
[subPredicatesAux addObject:predicate];
}
subPredicates = [subPredicatesAux copy];
return [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
}

Related

Use NSPredicate to filter by index

Basically, what I want to do is this:
NSArray *objectsAtIndex1 = #[[#[#"Foo", #"Bar"] objectAtIndex:1]];
but using NSPredicate instead, so it would look something like this (however this is not working):
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF[1] != null"]
NSArray *objectsAtIndex1 = [#[#"Foo", #"Bar"] filteredArrayUsingPredicate:predicate]
And of course, #"Foo" and #"Bar" are in reality unknown values (and could even be dictionaries or numbers). Is it possible to achieve this?
I solved it by using the predicateWithBlock: method on NSPredicate like this:
NSArray *fooBarArray = #[#"Foo", #"Bar"];
NSUInteger index = 1;
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [fooBarArray indexOfObject:evaluatedObject] == index;
}];
NSArray *objectsAtIndex1 = [fooBarArray filteredArrayUsingPredicate:predicate];
One caveat is however that the objects in fooBar-array needs to be unique for this to work, which is not perfect.

IN operator with NSPredicate and SBElementArray

Does the IN operator work for filtering SBElementArrays? I have been trying to use it but it always returns a NULL array.
My code (hexArray will typically have more elements):
SBElementArray *musicTracks = [libraryPlaylist fileTracks];
hexArray = [NSArray arrayWithObject: #"3802BF81BD1DAB10"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY %K IN %#",#"persistentID",hexArray];
NSLog(#"%#", [[musicTracks filteredArrayUsingPredicate:predicate] valueForKey:#"persistentID"]);
NSLog(#"%#", hexArray);
NSLog(#"%#", predicate);
Output:
2013-05-26 12:59:29.907 test[1226:403] (null)
2013-05-26 12:59:29.907 test[1226:403] (3802BF81BD1DAB10)
2013-05-26 12:59:29.908 test[1226:403] ANY persistentID IN {"3802BF81BD1DAB10"}
I have tried setting the predicate to:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY %K == %#",#"persistentID",hexArray];
Output:
2013-05-26 13:03:04.629 test[1258:403] (3802BF81BD1DAB10)
2013-05-26 13:03:04.630 test[1258:403] (3802BF81BD1DAB10)
2013-05-26 13:03:04.630 test[1258:403] ANY persistentID == {"3802BF81BD1DAB10"}
And this works fine. But I would like the IN functionality.
Instead of doing
persistentID IN ('abc', 'abc', 'abc', ...)
you can do
persistentID == 'abc' OR persistentID == 'abc' OR ...
It seems to work pretty fast.
NSMutableArray *subPredicates = [NSMutableArray arrayWithCapacity:persistentIDs.count];
for (NSNumber *persistentID in persistentIDs) {
[subPredicates addObject:pred(#"persistentID == %#", persistentID.hexValue)];
}
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
[tracks filterUsingPredicate:predicate];
NSLog(#"%ld", tracks.count);
Try using CONTAINS[c]
Ex:-
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY %# CONTAINS[c] %k",hexArray, #"persistentID"];
I ended up just looping through all the elements of hexArray and using an equality predicate on each pass. Probably not the most efficient, but it works.
for (NSString *hexID in hexArray){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"persistentID == %#",hexID];
iTunesTrack *track = [[musicTracks filteredArrayUsingPredicate:predicate] objectAtIndex:0];
[track duplicateTo:playlist];
}
Your predicate should be %K IN %# (without the ANY), if I understand your intention correctly (get all the tracks that have one of the IDs in the array).
For some reason, this doesn't work with SBElementArray, but you could simply convert it to a regular NSArray before applying the predicate (an NSSet should work too, and might be more efficient):
SBElementArray *musicTracks = [libraryPlaylist fileTracks];
NSArray *musicTracksArray = [NSArray arrayWithArray:musicTracks];
NSArray *hexArray = [NSArray arrayWithObjects: #"CE24B292556DB1BA", #"CE24B292556DB1F0", #"CE24B292556DB1C4", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K IN %#", #"persistentID", hexArray];
NSLog(#"%#", [[musicTracksArray filteredArrayUsingPredicate:predicate] valueForKey:#"persistentID"]);
Scripting Bridge technically supports the IN operator, in that it will construct a properly-formed Apple event for it, but most applications don't understand it. The best workaround is the chained OR tests as suggested by NSAddict.

How to modify this predicate so it handles multiple keywords efficiently

I have this predicate:
NSPredicate * thePredicateKeyword = [NSPredicate predicateWithFormat:#"any keywords.thekeyword beginswith [cd] %#", searchTerm];
Basically each business have many to many relationship with keywords.
But suppose I do not have one searchTerm. Say I have an array.
How would I do so?
I suppose I can just make predicate for each and combine them with or predicate, etc.
However, is there a way to more efficiently do this using in keywords or stuff like that?
What about a function that returns something like this:
-(NSPredicate *)createCompoundPredicateForSearchTerms:(NSArray *)searchTerms
{
NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
NSEnumerator *searchTermEnum = [searchTerms objectEnumerator];
NSString *searchTerm;
while (searchTerm = [searchTermEnum nextObject]) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"keywords.thekeyword beginswith [cd] %#", searchTerm];
[subPredicates addObject:predicate];
}
return [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
}
This is what I actually use. However, the anwer I chose is what inspire it.
NSArray * keywords = [searchTerm componentsSeparatedByString:#" "];
NSMutableArray * keywordPredicates = [NSMutableArray array];
for (NSString * aKeyword in keywords) {
NSPredicate * thePredicateKeyword = [NSPredicate predicateWithFormat:#"any keywords.thekeyword beginswith [cd] %#", aKeyword];
[keywordPredicates addObject:thePredicateKeyword];
}
NSPredicate * thePredicateKeyword = [NSCompoundPredicate orPredicateWithSubpredicates:keywordPredicates];
return thePredicateKeyword;

How to sort NSPredicate

I am trying to sort my array while using NSPredicate.. I have read other places that possibly using NSSortDescriptor could be an option. Having some trouble figuring this out.
I am attempting to sort my array by companyName.
Any advice appreciated, thanks
Greg
- (void)filterSummaries:(NSMutableArray *)all byNameThenBooth:(NSString*) text results:(NSMutableArray *)results
{
[results removeAllObjects];
if ((nil != text) && (0 < [text length])) {
if ((all != nil) && (0 < [all count])) {
NSPredicate *predicate = [NSPredicate predicateWithFormat: #"companyName contains[cd] %# OR boothNumber beginswith %#", text, text];
[results addObjectsFromArray:[all filteredArrayUsingPredicate:predicate]];
}
}
else {
[results addObjectsFromArray:all];
}
}
you have several options how to sort an array:
I'll show a NSSortDescriptor-based approach here.
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"companyName contains[cd] %# OR boothNumber beginswith %#",
text,
text];
// commented out old starting point :)
//[results addObjectsFromArray:[all filteredArrayUsingPredicate:predicate]];
// create a descriptor
// this assumes that the results are Key-Value-accessible
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"companyName"
ascending:YES];
//
NSArray *results = [[all filteredArrayUsingPredicate:predicate]
sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
// the results var points to a NSArray object which contents are sorted ascending by companyName key
This should do your job.
The filteredArrayUsingPredicate: function walks through your array and copies all objects that match the predicate into a new array and returns it. It does not provide any sorting whatsoever. It's more of a search.
Use the sorting functions of NSArray, namely sortedArrayUsingComparator:, sortedArrayUsingDescriptors:, sortedArrayUsingFunction:context: and the like, whichever serves you most.
Checkout NSArray Class Reference for details.
BTW: If you want to sort lexically, you may use sortedArrayUsingSelector:#selector(compare:) which will use NSString's compare: function to find the right order.

Shorter way to write NSPredicate format string for testing multiple properties?

Is there a shorter way to write the format string for a predicate equivalent to this:
[NSPredicate predicateWithFormat: #"key1 CONTAINS[cd] %# OR key2 CONTAINS[cd] %# OR key3 CONTAINS[cd] %#", searchString, searchString, searchString];
I have written a few predicate format strings like this, and I was thinking to simplify that by writing a method that takes an array of key paths and the search string to construct such a predicate. But I thought I’d ask if there is a built-in way to do this, before doing that.
NSCompoundPredicate is a subclass of NSPredicate and takes an NSArray of NSPredicate instances. However, this would mean that you still have to construct the NSPredicate objects (the subpredicates if you will) yourself. My suggestion is to write your own method (as you are planning to) but use NSCompoundPredicate as it is designed for this purpose.
- (NSPredicate *)predicateWithKeyPaths:(NSArray *)keyPaths andSearchTerm:(NSString *)searchTerm {
NSMutableArray *subpredicates = [[NSMutableArray alloc] init];
for (NSString *keyPath in keyPaths) {
NSPredicate *subpredicate = [NSPredicate predicateWithFormat:#"%K CONTAINS[cd] %#", keyPath, searchTerm];
[subpredicates addObject:subpredicate];
}
NSPredicate *result = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
[subpredicates release];
return result;}
I don't believe there is a shorter way. An alternative is to use NSCompoundPredicate's orPredicateWithSubpredicates: method. That's hardly shorter, but probably not as "boring" as having to concatenate strings.