Matching text field's value with array contents in objective c - ios

I have some arrays whose contents are picked from db.I want to match up the text i have entered in 'searchTextField' with those array's contents which is taken from DB.
For example: my array contains, myArray={'bat man','bat and ball','ball'};
if i have entered 'bat' in 'searchTextField'; it must show index of matching text in array(in this case index 0 and 1).
How can i achieve this..
Waiting for your help..

NSMutableArray *tempArray = [NSMutableArray arrayWithObjects:#"bat man",#"bat and ball",#"ball", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] 'bat'"];
NSArray *result = [tempArray filteredArrayUsingPredicate:predicate];
result array will be containing the filtered objects, from there you can get the index as:
[tempArray indexOfObject:/the object from result array, one by one/]
contains[c] means search will be case insensitive. For more on predicates: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html
EDIT
set the textField's delegate as self. Before that go to YourFile.h, there add UITextFieldDelegate. now in textFieldShouldReturn do this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
NSMutableArray *tempArray = [NSMutableArray arrayWithObjects:#"bat man",#"bat and ball",#"ball", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",textField.text];
NSArray *result = [tempArray filteredArrayUsingPredicate:predicate];
return YES;
}

Related

Obj-c - Filter array to return dictionaries in which a key contains values listed in NSMutableArray?

I have an array (allFriends) which returns a number of dictionaries (data for about 50 people). Each dictionary contains the key 'uid'. I want to filter allFriends so that all dictionaries in which uid contains the numbers 1,2,3, or 4 are returned.
How might I accomplish this? The numbers I want to filter with are returned in an array, and are grabbed like so:
NSMutableArray *friendUIDs = [self.friendData valueForKey:#"uid"];
This returns the data as: "1, 2, 3, 4"
No matter what I try however (thought NSPredicate would be the way to go), my code doesn't seem to want to let me filter with multiple values separated by a comma?
NSArray *filteredData = [self.allFriends filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(uid contains[c] %#)", friendUIDs]];
Hope I worded this correctly.
Your final predicate should look something like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.uid contains[c] %# OR SELF.uid contains[c] %#", #"1",#"2"];
If I understand the question correctly, this should work:
NSMutableArray *friendUIDs = [self.friendData valueForKey:#"uid"];
NSMutableString *predicateString = [NSMutableString string];
for (NSInteger i = 0; i < [friendUIDs count]; i++) {
if (i != 0) {
[predicateString appendString:#" OR "];
}
[predicateString appendFormat:#"SELF.uid contains[c] '%1$#'", friendUIDs[i]];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredData = [allFriends filteredArrayUsingPredicate:predicate];

Using predicate to find if string value exists

I have a NSMutableArray of objects with tag attributes assigned to them. I am trying to find if any of these objects have a tag assigned to them of the string value "a".
my code so far:
for (Object *object in self.array)
{
NSDictionary *attrs = [object propertyValue:#"attrs"];
NSString *tag = attrs[#"tag"];
}
Can I do something like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"a"];
NSArray *results = [self.array filteredArrayUsingPredicate:predicate];
not sure how it works?
Try this
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"tag == %#", #"a"];
NSArray *result = [NSMutableArray arrayWithArray:[self.array filteredArrayUsingPredicate:predicate]];
Use 'contains[c]' instead of '==' if you want to perform case-insensitive search.
If you want to filter for any other property, replace 'tag' with that property name.
You will need to do something more like :
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.property_name contains[c] '%#'", #"a"];
NSArray *result = [NSMutableArray arrayWithArray:[self.array filteredArrayUsingPredicate:predicate]];

Filter array by first letter of string property

I have an NSArray with objects that have a name property.
I would like filter the array by name
NSString *alphabet = [agencyIndex objectAtIndex:indexPath.section];
//---get all states beginning with the letter---
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
NSMutableArray *listSimpl = [[NSMutableArray alloc] init];
for (int i=0; i<[[Database sharedDatabase].agents count]; i++) {
Town *_town = [[Database sharedDatabase].agents objectAtIndex:i];
[listSimpl addObject:_town];
}
NSArray *states = [listSimpl filteredArrayUsingPredicate:predicate];
But I get an error - "Can't do a substring operation with something that isn't a string (lhs = <1, Arrow> rhs = A)"
How can I do this? I would like to filter the array for the first letter in name being 'A'.
Try with following code
NSPredicate *pred = [NSPredicate predicateWithFormat:#"SELF like %#", yourName];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];
EDITED :
NSPredicate pattern should be:
NSPredicate *pred =[NSPredicate predicateWithFormat:#"name beginswith[c] %#", alphabet];
Here is one of the basic use of NSPredicate for filtering array .
NSMutableArray *array =
[NSMutableArray arrayWithObjects:#"Nick", #"Ben", #"Adam", #"Melissa", #"arbind", nil];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] 'b'"];
NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
NSLog(#"beginwithB = %#",beginWithB);
NSArray offers another selector for sorting arrays:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Person *first, Person *second) {
return [first.name compare:second.name];
}];
If you want to filter array take a look on this code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", #"qwe"];
NSArray *result = [self.categoryItems filteredArrayUsingPredicate:predicate];
But if you want to sort array take a look on the following functions:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context;
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint;
- (NSArray *)sortedArrayUsingSelector:(SEL)comparator;
visit https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html
use this
[listArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
Checkout this library
https://github.com/BadChoice/Collection
It comes with lots of easy array functions to never write a loop again
So you can just do
NSArray* result = [thArray filter:^BOOL(NSString *text) {
return [[name substr:0] isEqualToString:#"A"];
}] sort];
This gets only the texts that start with A sorted alphabetically
If you are doing it with objects:
NSArray* result = [thArray filter:^BOOL(AnObject *object) {
return [[object.name substr:0] isEqualToString:#"A"];
}] sort:#"name"];

How to perform search on array if it has items matching then copy those items in another array in ipad app

I have a app in which i want searching. I have a array resultArray which contain all the things which display like
Book*bookObj=[resultArray objectAtIndex.indexPath.row];
NSString*test=bookObj.title;
I want to perform search on title item in resultArray if search text enter in textfield matches with title with any of the arrays then copy those all array values in testArray.
Use this as :
NSMutableArray *searchDataMA = [NSMutableArray new];
for (int i = 0; i < resultArray.count; i++) {
Book *bookObj=[resultArray objectAtIndex:i];
NSString*test=bookObj.title;
NSRange rangeValue1 = [test rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (rangeValue1.length != 0) {
if (![resultArray containsObject:test]) {
[searchDataMA addObject:test];
}
}
}
You have to take another array for this. this will add your object
for (Book * bookObj in resultArray) {
NSString *strName=[[bookObj.title]lowercaseString];
if ([strName rangeOfString:searchText].location !=NSNotFound) {
[arrTemp addObject:bookObj];
}
}
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate is exactly the function that you want. It will return a new array with only the elements that pass the test in the NSPredicate object.
For example:
NSArray *newArray = [oldArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Book *evaluatedObject, NSDictionary *bindings) {
//Do whatever logic you want to in here
return [evaluatedObject.title isEqualToString:theTitle];
}];
It works for me try this:
NSArray *fruits = [NSArray arrayWithObjects:#"Apple", #"Crabapple", #"Watermelon", #"Lemon", #"Raspberry", #"Rockmelon", #"Orange", #"Lime", #"Grape", #"Kiwifruit", #"Bitter Orange", #"Manderin", nil];
NSPredicate *findMelons = [NSPredicate predicateWithFormat:#"SELF contains[cd] 'melon'"];
NSArray *melons = [fruits filteredArrayUsingPredicate:findMelons];
NSPredicate *findApple = [NSPredicate predicateWithFormat:#"SELF beginswith 'Apple'"];
NSArray *apples = [fruits filteredArrayUsingPredicate:findApple];
NSPredicate *findRNotMelons = [NSPredicate predicateWithFormat:#"SELF beginswith 'R' AND NOT SELF contains[cd] 'melon'"];
NSArray *rNotMelons = [fruits filteredArrayUsingPredicate:findRNotMelons];
NSLog(#"Fruits: %#", fruits);
NSLog(#"Melons: %#", melons);
NSLog(#"Apples: %#", apples);
NSLog(#"RNotMelons: %#", rNotMelons);
Predicates also have more condition functions, some of which I have only touched on here:
beginswith : matches anything that begins with the supplied condition
contains : matches anything that contains the supplied condition
endswith : the opposite of begins with
like : the wildcard condition, similar to its SQL counterpart. Matches anything that fits the wildcard condition
matches : a regular expression matching condition. Beware: quite intense to run
The syntax also contains the following other function, predicates and operations:
AND (&&), OR (||), NOT (!)
ANY, ALL, NONE, IN
FALSE, TRUE, NULL, SELF
Still if don't understand take a look at this link;
Useful link

String search in string array in objective c

I want to search a specific string in the array of strings in objective c. Can somebody help me in this regard?
BOOL isTheObjectThere = [myArray containsObject: #"my string"];
or if you need to know where it is
NSUInteger indexOfTheObject = [myArray indexOfObject: #"my string"];
I strongly recommend you read the documentation on NSArray. It's best to do that before posting your question :-)
You can use NSPredicate class for searching strings in array of strings.
See the below sample code.
NSMutableArray *cars = [NSMutableArray arrayWithObjects:#"Maruthi",#"Hyundai", #"Ford", #"Benz", #"BMW",#"Toyota",nil];
NSString *stringToSearch = #"i";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",stringToSearch]; // if you need case sensitive search avoid '[c]' in the predicate
NSArray *results = [cars filteredArrayUsingPredicate:predicate];
This is the most efficient way for searching strings in array of strings
NSMutableArray *cars = [NSMutableArray arrayWithObjects:#"Max",#"Hai", #"Fine", #"Bow", #"Bomb",#"Toy",nil];
NSString *searchText = #"i";
NSArray *results = [cars filteredArrayUsingPredicate:predicate];
// if you need case sensitive search avoid '[c]' in the predicate
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"title contains[c] %#",
searchText];
searchResults = [cars filteredArrayUsingPredicate:resultPredicate];

Resources