Filter values from NSMutableArray using NSPredicate - objective-c

country=[[NSMutableArray alloc]initWithObjects:#"Afghanistan",
#"Albania",
#"Algeria",
#"American Samoa",
#"Andorra",
#"Angola",
#"Anguilla",
#"Antigua and Barbuda",
#"Argentina",
#"Armenia",
#"Aruba",
#"Ascension Island",
#"Australia",nil];
NSString *value=#"Al";
NSPredicate * predicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#",value];
NSArray *filterValue = [country filteredArrayUsingPredicate:predicate];
I have a NSMutableArray with list of countries.I tried to filter values with NSPredicate.It is not working.What is wrong with my code?any help will appreicated.thanks in advance

It should be:
NSString *value=#"Al";
NSPredicate * predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[cd] %#",value];
Notice that "value" is lowercase in both places that it's used.

Related

how can filter multilevel arrays for searching a string?

NSPredicate *predicate3 = [NSPredicate predicateWithFormat:#"ANY %K.%K.%K CONTAINS[c] %#",#"Assets",#"TFloorAssets",#"AssetNo",strSearch];
NSArray *filteredPendingList = [NSMutableArray arrayWithArray:[arrOfAllAssetsCategory filteredArrayUsingPredicate:predicate3]];
I am using above type of code for multilevel search ?
Use a collection operator:
[NSPredicate predicateWithFormat:#"ANY Assets.#unionOfArrays.TFloorAssets.AssetNo contains[c] %#", strSearch]
Or a subquery:
[[NSPredicate predicateWithFormat:#"SUBQUERY(Assets, $asset, ANY $asset.TFloorAssets.AssetNo contains[c] %#).#count > 0", strSearch]
Or a two subqueries:
[NSPredicate predicateWithFormat:#"SUBQUERY(Assets, $asset, SUBQUERY($asset.TFloorAssets, $tFloorAsset, $tFloorAsset.AssetNo contains[c] %#).#count > 0).#count > 0", strSearch]
Use "compound predicate" like below
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:
#[predicateEventsByAsset, predicateEventsByFloorAsset ,predicateEventsByAssetNo]];
self.filteredEventsArray = [self.eventsArray filteredArrayUsingPredicate:predicate];

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;

NSPredicate concatenating attributes

I m trying to figure out how to concatenate attribute names. I have a county and a district attribute that I want to query like
[NSPredicate predicateWithFormat:#"county + district contains[cd] %#",searchBar.text]
gives me unimplemented SQL generation for predicate error. and I am not sure how to implement NSPredicate.
Thanks
This should give you an idea of how to do some more complicated searching. It will match queries for "county district", "district county", etc.
NSArray *searchTerms = [searchBar.text componentsSeparatedByString:#" "];
NSString *predicateFormat = #"(county contains[cd] %#) OR (district contains[cd] %#)";
NSPredicate *predicate;
if ([searchTerms count] == 1) {
NSString *term = [searchTerms objectAtIndex:0];
predicate = [NSPredicate predicateWithFormat:predicateFormat, term, term];
} else {
NSMutableArray *subPredicates = [NSMutableArray array];
for (NSString *term in searchTerms) {
NSPredicate *p = [NSPredicate predicateWithFormat:predicateFormat, term, term];
[subPredicates addObject:p];
}
predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
}
[fetchRequest setPredicate:predicate];
See Cocoa Is My Girlfriend: Adding iTunes-style search to your Core Data application for more explanation.
I ended up implementing another field as concatenating the two variables(district+country) and perform the query on that variable.
I did something similar and concluded that like cekisakurek, the best method was to concatenate the fields into a common field (more relevant for first/last name)
- (NSString *)fullName {
return [NSString stringWithFormat:#"%# %#", self.firstName, self.lastName];
}
and then filtered on this field using 'contains[cd]'
[NSPredicate predicateWithFormat:#"fullName contains[cd] %#", self.searchBar.text];
[NSPredicate predicateWithFormat:#"county contains[cd] %# AND district contains[cd] %#",searchBar.text,searchBar.text];
Just try the above lines of code, it would helps you.

Problem filtering NSArrayController

I have problem filtering an NSArrayController. Content Array is bound to an NSMutableArray holding NSDictionaries. I want to filter all NSDictionaries whose "name" key equals "a".
I run these two lines when my app launches but nothing gets filtered.
NSPredicate *filter = [NSPredicate predicateWithFormat: #"name like %#", #"a"];
[arrayController setFilterPredicate: filter];
NSPredicate *filter = [NSPredicate predicateWithFormat: #"name=%#", #"a"];
[arrayController setFilterPredicate: filter];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"(name contains[cd] $a)"];
[arrayController setFilterPredicate: filter];