NSPredicate and BeginsWith - ios

I would like to figure out the NSPredicate that will search my Core data for words that begins with:
For example:
description field in the core data has text like this:
My name is Mike
My name is Moe
My name is Peter
My name is George
If I search 'My name is' I need to get the 3 lines
If I search 'My name is M' I need to get the first 2 lines
I tried the code below, but can't get what I need. My guess I need a regular expression, but not sure how to do it.
[NSPredicate predicateWithFormat:#"desc beginswith [cd] %#",word];

I did it this way recently and worked fine. Try it out. I see I don't have [cd] and beginswith but contains. You could give it a try.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains %#", textField.text];
NSArray *list = [allWords filteredArrayUsingPredicate:predicate];
for(NSString *word in list){
NSLog(#"%#",word);
}
After reading the comments on the starting post:
First of all, you should split up the words in the string from the textfield:
NSArray *myWords = [textField.text componentsSeparatedByString:#" "];
Then doing the same like you first would:
for(NSString *wordFromTextField in myWords){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains %#", wordFromTextField];
NSArray *list = [allWords filteredArrayUsingPredicate:predicate];
for(NSString *word in list){
NSLog(#"%#",word);
}
}
Instead of NSLogging the words you could add them to an array of course.

Related

NSPredicate on NSArray of NSDictionary

Imagine you have the following structure for an NSArray of NSDictionary objects:
#define kFlameText #"text"
#define kFlameRelation #"relation"
NSArray* data = #[#{kFlameText:#"TextFlame1", kFlameRelation:#"Relation1"}, #{kFlameText:#"TextFlame2", kFlameRelation:#"Relation2"}, #{kFlameText:#"TextFlame3", kFlameRelation:#"Relation3"}}
You want to use a NSPredicate to extract the dictionary located in second position in your NSArray of NSDictionary based on the NSString #"Relation2"
You tried multiple times, with you last attempt being:
NSPredicate* sortFlames = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#", #"Relation2"];
But you are still not there, you still get the following error message:
How would you make it work?
This predicate should do the trick:
NSPredicate *sortFlames = [NSPredicate predicateWithFormat:#"SELF.%K CONTAINS[cd] %#", kFlameRelation, #"Relation2"];
The %K is for the dynamic property name, more info here.

Filter Search through NSArray by letter not working. IOS

I am trying to filter / search through an NSArray with the text from my UITextfeild.text
If I try to search a match string the filter works but my filtered array always comes out empty as I type the letters in the text-field.
NSArray *testArray = [NSArray arrayWithObjects:#"testmailone#test.com",#"a#test.com",#"b#testing.com",#"h#fgdfgd",#"helloMan#test.com", #"dfsdfsdfsdfsdfs#dsfdfs",nil];
NSPredicate *predicatedString = [NSPredicate predicateWithFormat:#"SELF == %#", self.addHungryPersonTF.text];
NSArray *resultsArrayString = [testArray filteredArrayUsingPredicate:predicatedString];
NSLog(#"resultsArrayString%#",resultsArrayString);
This returns null but if I change the string to match against another set string like so:
NSString *matches = [NSString stringWithFormat:#"testmailone#test.com"];
NSLog
resultsArrayString(
"testmailone#test.com"
)
It then works an the array becomes populated with matched string.
Anyone have any ideas of why it will not search through my NSArray by letter? When I type it should be checking the array correctly?
NSPredicate *predicatedString = [NSPredicate predicateWithFormat:#"SELF CONTAINS %#", self.addHungryPersonTF.text];
//keep this one for get all the strings which contains the substring or string itself
NSPredicate *predicatedString = [NSPredicate predicateWithFormat:#"SELF BEGINS %#", self.addHungryPersonTF.text];
//keep this one for sting starts with the key word

Searching an Array using NSPredicate method predicateWithFormat

Currently trying to setup a search would search an Array (bakeryProductArray) which looks like this
"Tea Loaf",
Tiramusu,
"Treacle Loaf",
Trifle,
"Triple Chocolate Brownie",
Truffles,
"Various sponges",
"Viennese Whirls",
"Wedding Cakes"
with what the users types into the UISearchbar. I am unclear on how to represent each item in the array in the CFString.
The code I currently have is.
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
{
searchSearch = [NSPredicate predicateWithFormat:#"self CONTAINS[cd]",searchText];
//#"%K CONTAINS[cd] %#"
searchResults = [bakeryProductArray filteredArrayUsingPredicate:searchSearch];
NSLog(#"Filtered Food Product Count --> %d",[searchResults count]);
}
Can answer any questions and supply more code if needed.
Is this what your are looking for?
NSArray *bakeryProductArray = #[#"Tea Loaf", #"Tiramusu", #"Treacle Loaf", #"Trifle"];
NSString *searchText = #"tr";
NSPredicate *searchSearch = [NSPredicate predicateWithFormat:#"self CONTAINS[cd] %#", searchText];
NSArray *searchResults = [bakeryProductArray filteredArrayUsingPredicate:searchSearch];
NSLog(#"%#", searchResults);
// "Treacle Loaf",
// Trifle
This finds all strings that contain the given search string (case insensitive).
Alternatively, you can use "=" or "BEGINSWITH", depending on your needs.
(More information about predicates in the "Predicate Programming Guide" .)

How to filter a NSArray

Hey i want to filter an NSArray. In this Array is a lot of information like name, town, telephonenumber, and so on. But some towns are twice or three times in the array.
I have property with a town in it.
So i want only those objects from the arry which match with the property.
For example:
in the Array stands:
Frank, New York, 123456
Oliver, New York, 123456
Thomas, Boston, 123456
and when the property is New York i want olny objects 1 and 2.
Does anyone has an idea how i can do it?
This is my code:
NSString *filterString = newsArticle;
NSPredicate *prediacte = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"Ort == '%#'",filterString]];
newsTownArray = [news filteredArrayUsingPredicate:predicate];
and when i come to the line:
cell.textLabel.text=[[newsTownArray objectAtIndex:indexPath.row] objectForKey:"Name"];
You need to use NSPredicate for this.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"town == 'New York'"];
[yourArray filterUsingPredicate:predicate];
Dynamically you can create predicate like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"town == '%#'",yourInput]];
Here yourInput is a NSString which holds the required town name.
Please check these articles for more details:
codeproject
useyourloaf
Use this code
NSMutableArray *subpredicates = [NSMutableArray array];
for(NSString *term in arryOfWordsToBeSearched) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"self contains[cd] %#",term];
[subpredicates addObject:p];
}
NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
result = (NSMutableArray*)[arryOfDummyData filteredArrayUsingPredicate: filter];
However you can do it within an array with the use of NSPredicate, but I will suggest to do bit differently, this will add up to your code and good programming way.
Create a custom class Person having these properties name, city and telephone.
Create an array that will store objects of Person.
After this you can manipulate/ filter / sort etc quite easily.
NSString *filterCity=#"Delhi";
NSMutableArray *yourArray=[NSMutableArray arrayWithArray:self.persons];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"city == '%#'",filterCity]];
[yourArray filterUsingPredicate:predicate];
NSLog(#"Filtered");
for (Person *per in yourArray) {
NSLog(#"Name: %#, City: %#, Telephone: %#",per.name, per.city, per.telephone);
}

NSPredicate contains search in a string that contains number and letters

I have to use NSPredicatefor search through some Core Data objects. But the key nameof the custom object could contains both numbers then letters.
The string could look like:John 1234 Lennonor Ringo Starr.
I normally would use the predicate NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Any name CONTAINS[cd] %#",searchString];
But, if I search for John Lennon the predicate don't return anything, because it can't compare if it contains the characters John Lennon, since is missing the 1234. Any tips what kind of predicate I can use?
You can tokenise your query , maybe as simple as
NSArray *tokens = [querystring componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Then construct a compound predicate.
NSMutableArray *predarray = [NSMutableArray array];
for(NSString *token in tokens)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Any name CONTAINS[cd] %#",token];
[predarray addObject:predicate];
}
NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:predarray];
And feed that to your query
In real life I would run a bit of validation against each token to check its going to make a valid predicate and wont crash or create a security risk. e.g Strip special chars like "* []"
EDIT:Corrected predicate type to work with questions situation.
Try using LIKE instead of contains, and then you can use wild cards, for instance John*Lennon should match a string that starts with John and ends with Lennon with any number of other characters in between. You can use ? Instead which would match only one character for each question mark if you want more control over what's matched.
You could split the search string up into an array of strings and then switch your predicate to look for any string in the name:
NSArray *strings = [searchString componentsSeparatedByString:#" "];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"ANY %# IN name",strings];

Resources