Mumthezir VP
Mumthezir VP

Reputation: 6551

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

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..

Upvotes: 0

Views: 1723

Answers (1)

devluv
devluv

Reputation: 2017

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;
}

Upvotes: 4

Related Questions