Grouping in search display controller - iphone

In my Core Data app, I have an entity Person with names as attribute.
I used following predicate logic to search the names.
It displays names when we search with a word.
well but I want two groups of searched names as
Word containing anywhere in the name
Name starts withe the word.
both groups I want. How?
NSString *searchfilter = [NSString stringWithFormat:#"*%#*",savedSearchTerm_];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"word like[c] %#", searchfilter];
[fetchRequest setPredicate:filter];

Your example should work for #1.
word is anywhere anywhere in the name:
NSString *searchfilter = [NSString stringWithFormat:#"*%#*",savedSearchTerm_];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"word like[c] %#", searchfilter];
[fetchRequest setPredicate:filter];
name starts with the word:
NSString *searchfilter = [NSString stringWithFormat:#"%#*",savedSearchTerm_];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"word like[c] %#", searchfilter];
[fetchRequest setPredicate:filter];

i think you have 2 options here:
1) - (id)initWithFetchRequest:(NSFetchRequest *)fetchRequest managedObjectContext:(NSManagedObjectContext *)context sectionNameKeyPath:(NSString *)sectionNameKeyPath cacheName:(NSString *)name pass sectionNameKeyPath: by what you want to group
2) group after selecting - (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error

Related

Search NSArray using NSPredicate

I am new to NSPredicate so sorry if I am asking stupid question. I have two NSArray (keyArray and valueArray). I have to find match in valueArray using keyArray. Below code is working fine but I have to search one by one. Any way to search an array using a different key array.
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:#"companyId = %#", [[[self selectedCompanies] objectAtIndex:0] companiesIdentifier]];
NSLog(#"Users: %#", [[[self userData] users] filteredArrayUsingPredicate:userPredicate]);
NSPredicate *userPredicate1 = [NSPredicate predicateWithFormat:#"companyId = %#", [[[self selectedCompanies] objectAtIndex:1] companiesIdentifier]];
NSLog(#"Users: %#", [[[self userData] users] filteredArrayUsingPredicate:userPredicate1]);
You can do:
NSPredicate *userPredicate1 = [NSPredicate predicateWithFormat:#"companyId IN %#", [[self selectedCompanies] valueForKey:#"companiesIdentifier"];
NSLog(#"Users: %#", [[[self userData] users] filteredArrayUsingPredicate:userPredicate1]);
What happens here is we take the companiesIdentifier of all selected companies and match users based on those identifiers.
valueForKey: on an array object returns an array with the value of the required key for each object in the array. IN is a predicate operator searching in a collection (array, set, etc.).

NSPredicate using OR error

First time building an NSPredicate.
I would like to search a managedobjectcontext using this logic:
Search for a, grab all matches
Search for b, grab all matches, etc....
Nsarray *results = (has all a results, b results, etc);
My attempted predicate is:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name== %# OR name == %# OR name == %#",a,b,c];
However I get errors with this predicate...
Edited: Sample method I wrote
-(NSPredicate*)parsePartsIntoAPredicate:(NSMutableArray*)inputPartsNames{
NSSet *keys=[NSSet setWithArray:inputPartsNames];
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"any self.#name in %#", keys];
NSLog(#"predicate = %#",predicate);
return predicate;
}
Clarify: I have a database of cars (20,000) Each car has multiple parts. I want to find all cars that have part a, and all cars that have part b, and all that have part c. Then I want to return an array with cars with part a, b, c, etc...
If you think there is a better way let me know, but I am approaching this backwards. I am saying
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Cars" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[self parsePartsIntoAPredicate:inputParts]];
NSError *error;
NSArray *records = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
What am I doing wrong?
NSString *key;
NSMutableArray *tempArray;
NSPredicate *searchForName = [NSPredicate predicateWithFormat:#"name = %#", key];
NSArray *filterArray = [tempArray filteredArrayUsingPredicate:searchForName];
NSLog(#"%#",filterArray);
Where key is your searchKeyword, tempArray is your CompleteArray in which data is present.
Use Like this. Please put your data.
Use this
NSPredicate* predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"%# '%#'", #"SELF contains[c] ",searchText]];
To fetch all Cars objects that have a name which is one of the strings in the keys set or array, use
[NSPredicate predicateWithFormat:#"name IN %#", keys]

What does Unable to generate SQL for predicate (_STRING PREDICATE_) (problem on RHS) mean?

I'm trying to develop an app for iPhone using Core Data and I'm using a very basic predicate to grab objects. (i.e. attribute_name==string)
I've checked the model to make sure the attribute names are correct and I know from this SO question that RHS means "Right Hand Side," which leads me to the "string" part. I'm creating the format string using
NSString *predicateString = [NSString stringWithFormat:#"attribute_name==%#", string];
Then to fetch, I'm using this:
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:_entityName inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
What am I missing? What could cause this error to occur?
Thanks.
You need to quote the string if you really want to use the NSString stringWithFormat: message or you could use the NSPredicate predicateWithFormat: message with the formatting and arguments because it will "do the right thing" with the rhs in your situation (I would suggest that you use the NSPredicate method without the quotes)
NSString *predicateString = [NSString stringWithFormat:#"attribute_name==\"%#\"", string];
You're doing this wrong. You should not be creating a format string.
I'm guessing (based on your reaction to #Brent's answer) that you're doing something like this:
NSString *predicateString = [NSString stringWithFormat:#"foo == \"%#\"", bar];
NSPredicate *p = [NSPredicate predicateWithFormat:predicateString];
Don't do that.
Do this instead:
NSPredicate *p = [NSPredicate predicateWithFormat:#"foo == %#", bar];
The first will fail if bar happens to contain a " character. The second will not.

fetching objects from core data not in a set

I'm trying to fetch objects from core data that are not in a given set, but I haven't been able to get it to work.
For instance, suppose that we have a core data entity named User, which has a few attributes such as userName, familyName, givenName, and active. Given an array of strings representing a set of usernames, we can easily fetch all the users corresponding to that list of usernames:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User"
inManagedObjectContext:moc];
[request setEntity:entity];
NSArray *userNames = [NSArray arrayWithObjects:#"user1", #"user2", #"user3", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"userName IN %#", userNames];
[request setPredicate:predicate];
NSArray *users = [moc executeFetchRequest:request error:nil];
However, I want to fetch the complement of that set, i.e., I want all the users in core data that don't have the usernames specified in the userNames array. Does anyone have an idea how to approach this issue? I thought it would be simple enough to add a "NOT" in the predicate (i.e., "userName NOT IN %#"), but Xcode throws an exception saying the predicate format could not be parsed. I also tried using the predicate builder available for fetch requests with no luck. The documentation wasn't particularly helpful either. Suggestions? Comments? Thanks for all your help :)
In order to find the objects that aren't in your array, all you have to do is something like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (userName IN %#)", userNames];
That should return a request of all the objects without the ones you specified
I am not strong at core data/objective-c but the predicate should be like the following statement;
[predicateFormat appendFormat:#"not (some_field_name in {'A','B','B','C'})"];
An example:
NSMutableString * mutableStr = [[NSMutableString alloc] init];
//prepare filter statement
for (SomeEntity * e in self.someArray) {
[mutableStr appendFormat:#"'%#',", e.key];
}
//excluded objects exist
if (![mutableStr isEqual:#""])
{
//remove last comma from mutable string
mutableStr = [[mutableStr substringToIndex:mutableStr.length-1] copy];
[predicateFormat appendFormat:#"not (key in {%#})", mutableStr];
}
//...
//use this predicate in NSFetchRequest
//fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateFormat];
//...
Here's another useful example, showing how to take a list of strings, and filter out any which DON'T start with the letters A-Z:
NSArray* listOfCompanies = [NSArray arrayWithObjects:#"123 Hello", #"-30'c in Norway", #"ABC Ltd", #"British Rail", #"Daily Mail" #"Zylophones Inc.", nil];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:#"NOT (SELF MATCHES[c] '^[A-Za-z].*')"];
NSArray *filteredList = [listOfCompanies filteredArrayUsingPredicate:bPredicate];
for (NSString* oneCompany in filteredList)
NSLog(#"%#", oneCompany);
I use this kind of NSPredicate when I'm populating a UITableView with an A-Z index, and want an "everything else" section for items which don't start with a letter.

Objective-C: NSPredicate LIKE doesn't like spaces. Is there an escape sequence to replace blanks with?

I have a NSPredicate that looks like this:
NSPredicate *likePredicate3= [NSPredicate predicateWithFormat:#"synonyms LIKE[cd] %#",[NSString stringWithFormat:#"%#", searchText]];
I apply it to an NSArray of objects of a class that has the 'synonyms' property.
It works fine when the searchText is a whole word such as "Thanks". However if I try to use strings with space in them such as 'Thank you', it fails and the predicate search does not find the match in the array.
Is there a way to ask NSPredicate to work with words that have a blank space(s) in them?
thanks.
In principle, what you are doing should work. I ran this example:
NSString *search = #"a b";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF LIKE[cd] %#",
[NSString stringWithFormat:#"%#", search]];
NSArray *array = [[NSArray arrayWithObjects:#"a b", #"ä B", #"ccc", nil]
filteredArrayUsingPredicate: predicate];
NSLog(#"result: %#", array);
Output is:
Running…
2010-02-04 20:05:41.770 predicate2[74163:a0f] result: (
"a b",
"\U00e4 b"
)
Maybe your searchString isn't what you think it is...