iOS: displaying JSON Array in UISearchBar - ios

i have a JSON Dict in this format
{
"382" : "sudhir kumar",
"268" : "David ",
"385" : "aayush test",
"261" : "Mike watson",
"277" : "TestDrivers Driver",
"381" : "sudhir kumar",
"380" : "sudhir kumar",
"383" : "asdfgh asdfgh",
"376" : " "
}
I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected
I am using the following code it filtered name but not their related ID's with name
My code is:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
tempArray = [NSArray arrayWithArray:DriverNameArray];
//NSString *stringToSearch = textField.text;
tempId = [NSArray arrayWithArray:DriverIdArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[c] %#",searchText]; // if you need case sensitive search avoid '[c]' in the predicate
//NSPredicate * predicateid = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[c] %#",stringToSearch];
NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
if (tempresults.count > 0)
{
tempArray = [NSArray arrayWithArray:tempresults];
tempId = [NSArray arrayWithArray:tempresults];
}
[SEarchTable reloadData];
//return YES;
}

You have not posted code pertaining to what you've already tried, so I won't post code that directly gives you the solution to your question.
Your best bet is to create an array of dictionaries holding a value for the names and a value for the ID. When you display your data, display the names from the array by myArray[#"name"] convention. You can then get the index of that object and then run [myArray objectAtIndex:myCalculatedIndex][#"id"] to get the ID.
There are actually many ways to solve this problem, but this is one of them.

Related

IOS:UISerachBar Filter name but not the related id with it

i have a JSON Dict in this format
{
"382" : "sudhir kumar",
"268" : "David ",
"385" : "aayush test",
"261" : "Mike watson",
"277" : "TestDrivers Driver",
"381" : "sudhir kumar",
"380" : "sudhir kumar",
"383" : "asdfgh asdfgh",
"376" : " "
}
I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected
I am using the following code it filtered name but not their related ID's with name
My code is:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
tempArray = [NSArray arrayWithArray:DriverNameArray];
//NSString *stringToSearch = textField.text;
tempId = [NSArray arrayWithArray:DriverIdArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[c] %#",searchText]; // if you need case sensitive search avoid '[c]' in the predicate
//NSPredicate * predicateid = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[c] %#",stringToSearch];
NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
if (tempresults.count > 0)
{
tempArray = [NSArray arrayWithArray:tempresults];
tempId = [NSArray arrayWithArray:tempresults];
}
[SEarchTable reloadData];
//return YES;
}
It always returns the same id for all the filtered names
Create NSarray of NSdictionary containing id and name
MasterArray :
(
0{ id = "382" , drivername = "sudhir kumar"}
1{ id = "383" , drivername = "sudha mishra"}
.
.
n{ id = "384" , drivername = "sudesh pandit"}
)
whatever search result you will get in Your DriverNameArray. Iterate for loop through that and compare driver name with MasterArray
:
for(i = 0; i< DriverNameArray.count , i++)
{
//take driver name from search result array
NSString * driverName = [DriverNameArray objectAtIndex:i];
for(j = 0; j< MasterArray.count , j++){// search driver name in MasterArray
NSDictionary *driverInfoDic = [MasterArray objectAtIndex:j];
if(driverName isEqualToString:[driverInfoDic objectForKey:#"drivername"])
NSString *driverId = [driverInfoDic objectForKey:#"Id"];//use this driver id by storing it in DiverIdArray
}
}
You are filtering only Drivers' names array, which is not primarily connected with Drivers' ids array. I suggest you joining id, and name into a dictionary and storing it in one array. So that, whenever you filter it with name, or id the rest info will be stored in one object
#property (nonatomic, strong) NSMutableArray *allElements
#property (nonatomic, strong) NSArray *filteredArray;
`
for (int i=0; i < 10; i++) { //Just simple example
NSDictionary *dictionary = #{#"name": DriverNameArray[i], #"id": DriverIdArray[i] };
[self.allElements addObject:dictionary];
}
And in your searchbar delegate you can use:
NSArray *copyArray = [self.allElements copy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name BEGINSWITH %#", searchText];
NSArray *filteredArray = [copyArray filteredArrayUsingPredicate:predicate];
self.filteredArray = filteredArray;
[self.tableView reloadData];

How to search something in NSMutableDictionary

Hello I have a NSMutableArray like this
Contactarray (
{
"firstNAme"="name1"
"lastName"="name2"
"phoneNumber"="12345678902";
}
{
"firstNAme"="name1"
"lastName"="name2"
"phoneNumber"="12345678902";
}
I want to search the person when I type the person name in my UITextField. Then the filtered UItableView should be loaded. This NSMutableArray contains NSMutableDictionaries.
How can I find the matching object from these objects?
Lets say I want to search all name1 people. Then I want to find all the objects containing "name1" and those objects should fill to another array to load the UITableview
Please help me.
Thanks.
UPDATE
This is my contacts array
<__NSArrayI 0x7b601f70>(
firstname = Kate;
lastName = Bell;
phone = "(415) 555-3695";
userimg = "<UIImage: 0x7b67b3a0>";
};
{
firstname = Kate;
lastName = Bell;
phone = "(415) 555-3695";
userimg = "<UIImage: 0x7b67b3a0>";
},
This is my code for search
`
[playlistArray removeAllObjects];
NSArray *contacts=[[NSArray alloc] initWithArray:mutArraySearchContacts];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"firstname = %# OR lastName = %#",currentSrchStr,currentSrchStr];
playlistArray=[contacts filteredArrayUsingPredicate:filter];
[self performSelectorInBackground:#selector(playlistsLoaded) withObject:nil];
`
But my playlistArray is empty.
`
(lldb) po playlistArray
<__NSArrayI 0x7b74adf0>(
)
`
What is the wrong I have done here?
No need to iterate while you use NSPredicate. Try this.
NSPredicate * myPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"SELF['firstNAme'] contains '%#' || SELF['lastName'] contains '%#'",currentSrchStr,currentSrchStr]];
NSArray *filterArray = [mutArraySearchContacts filteredArrayUsingPredicate:myPredicate];
NSLog(#"filterArray %#", filterArray);
Update 1:
Modify your predicate with CONTAIN[C] for case insensitive, like
NSPredicate * myPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"SELF['firstNAme'] CONTAINS[c] '%#' || SELF['lastName'] CONTAINS[c] '%#'",currentSrchStr,currentSrchStr]];
Hope this helps you !!
NSArray *contacts = ...; //your array of NSDictionary objects
NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"firstName == %#", #"name1"]];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:filter];
If you need to search with more condition, like full name:
NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"firstName == %# OR lastName == %#" ,#"name1", #"name2"]];
Here is Predicate Programming Guide, which illustrates more advanced features.
You can use keysOfEntriesPassingTest: method to find all keys where the value equals #"test".
In the implementation below only the first key will be found. If you need all keys where the object is #"Test", do not assign *stop.
NSString *target = #"test";
NSSet *keys = [myDictionary keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop)
{
return (*stop = [target isEqual:obj]);
}];
when u get the key you can proceed further.

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

Plist NSPredicate in iOS

I have a plist working with a search display controller which contains an array of dictionaries with some data members like.
<root> (array)
<"Item 0"> (dictionary)
<"Name"></"Name" (String)
<"Work"></"Work"> (String)
<"Age"></"Work"> (Number)
</"Item 0">
<"Item 1">
....
</"Item 1">
</root>
I would like to use an NSPredicate to filter all the names that match with the search criteria. For example searching "an" for all names will yield "Sandy" and "Alexander."
So far I've tried things like:
NSPredicate *p = [NSPredicate predicateWithFormat:#"Name == %#",
filterText];
Results = [data filteredArrayUsingPredicate:p];
Any ideas? Thanks.
Use CONTAINS in NSPredicate
Below code gives case sensitive search
NSPredicate *p = [NSPredicate predicateWithFormat:#"Name CONTAINS %#",
filterText];
Results = [yourPlistDataArray filteredArrayUsingPredicate:p];
Below code gives case insensitive search
NSPredicate *p = [NSPredicate predicateWithFormat:#"ANY Name CONTAINS %#",
filterText];
Results = [yourPlistDataArray filteredArrayUsingPredicate:p];
EDIT : Refer more here
this can show you the very generic type of the searching in any NSArray. it is adjusted to your NSDictionary items currently, but you can create even more complex conditions here to filter it.
NSArray *originalArray = ...;
NSString *searchText = ...; // this is a parameter only, it can be set freely
NSArray *_filteredArray = [originalArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSDictionary *_dataRow = (NSDictionary *)evaluatedObject;
return ([[[_dataRow valueForKey:#"Name"] lowercaseString] rangeOfString:[searchText lowercaseString]].location != NSNotFound);
}]];
NSLog (#"%#", _filteredArray);

Resources