This code is the search code
- (void) searchTableView {
NSLog(#"4");
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:#"Countries"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
//NSLog(#"Count - %d",[copyListOfItems count]);
[searchArray release];
searchArray = nil;
}
I want to implement this type of search in my array but i am getting error in below line.
[searchArray addObjectsFromArray:array];
when control comes on this line application shutdown every time can any one help me ?
Thanks
That line will give you an error only if array has nothing in it(nil value).
So check what is the value of array using nslog.
Related
I have a plist which contain urdu language Words and also have English language words.as below screenshot
Now my Code is to fetch data is given Below
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[words removeAllObjects];
[means removeAllObjects];
NSString *path = [[NSBundle mainBundle] pathForResource:
#"urdutoeng" ofType:#"plist"];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithContentsOfFile:path];
for (int i=0; i<[array2 count]; i++) {
NSDictionary* dict = [array2 objectAtIndex:i];
[words addObject:[dict valueForKey:#"Urdu"]];
[means addObject:[dict valueForKey:#"English"]];
[Types addObject:[dict valueForKey:#"Nature"]];
}
}
This part of code work fine for me as my below screen shot
Now problem is when i search any words through searchbar it return Empty result beacuse my search array contain words in Different Formate my code for search array is
listOfItems = [[NSMutableArray alloc] init];
NSDictionary *countriesToLiveInDict = [NSDictionary dictionaryWithObject:words forKey:#"Countries"];
[listOfItems addObject:countriesToLiveInDict];
copyListOfItems = [[NSMutableArray alloc] init];
My Searchbar code is
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText
{
[copyListOfItems removeAllObjects];
NSLog(#"listOfItemsdata :%#",listOfItems);
for (NSString *cellLabel in [[listOfItems objectAtIndex:0] objectForKey:#"Countries"])
{
NSComparisonResult result = [cellLabel compare:searchText options: (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[copyListOfItems addObject:cellLabel];
}
}
}
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
NSLog(#"searchstring :%#",searchString);
[self filterContentForSearchText:searchString];
return YES;
}
When i Nslog the listOfItems Array it show text some thing like
NSLog(#"listOfItemsdata :%#",listOfItems);
listOfItemsdata :(
{
Countries = (
" \U0627\U0628",
" \U0627\U0628 \U0628\U06be\U06cc",
" \U0627\U0628 \U062a\U0628",
" \U0627\U0628 \U062a\U06a9",
" \U0627\U0628 \U062c\U0628 \U06a9\U06c1",
" \U0627\U0628 \U0633\U06d2",
Its show that my data goes in some other formate thats why searchbar is unable to search it.
Any help or Suggestion will be appriated.Thanks
All the Urdu entries in the plist have a space as first character. This is the reason that searching always produced an empty list.
As a workaround, one can remove leading and trailing spaces from the entries before comparing:
for (NSString *cellLabel in [[listOfItems objectAtIndex:0] objectForKey:#"Countries"])
{
NSString *trimmed = [cellLabel stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSComparisonResult result = [trimmed compare:searchText options: (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[copyListOfItems addObject:cellLabel];
}
}
I am trying to add a UISearchBar to my UITableView.
This is the method they use to search:
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:#"Countries"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
But I don't have a dictionary, I just want to search in my array 'exerciseArray' which is init like this:
NSString *path = [[NSBundle mainBundle]pathForResource:#"data" ofType:#"plist"];
NSMutableArray *rootLevel = [[NSMutableArray alloc]initWithContentsOfFile:path];
self.exerciseArray = rootLevel;
[rootLevel release];
When I NSLog it, I get:
exerciseArray: (
{
exerciseName = "Balance Board";
},
{
exerciseName = "Barbell Seated Calf Raise";
},
{
exerciseName = "Calf Press On The Leg Press Machine";
},
{
exerciseName = "Calf Raises- With Bands";
},
So can anyone help me modify the search method to fit the array I have? It seems to have a key in it.
I tried this but it did not work and crashed at line NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
with error *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary rangeOfString:options:]: unrecognized selector sent to instance 0x2d6450
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSLog(#"exerciseArray: %#", exerciseArray);
for (NSString *sTemp in listOfItems)
{
if (sTemp) {
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
}
}
Looks like you have an array of dictionaries with one key/value pair in each dictionary (exerciseName). so for your dataset, it should be this:
for (NSDictionary *dictionary in exerciseArray)
{
NSArray *array = [dictionary objectForKey:#"exerciseName"];
[searchArray addObjectsFromArray:array];
}
...
If you post your VC code related to the array and also your tableview datasource methods, I have can modify it and show you what you need to do.
For searching from table view i have tried this and i got success hope it will help you......
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
self.searching=NO;
NSString *originalString;
[self.filteredProductArray removeAllObjects];
for (int i=0; i<self.exerciseArray.count; i++)
{
originalString=[[[self.exerciseArray objectAtIndex:i] objectForKey:#"exerciseName"] lowercaseString];
if (!([originalString rangeOfString:[searchText lowercaseString]].location==NSNotFound))
{
[self.filteredProductArray addObject:[self.exerciseArray objectAtIndex:i]];
}
}
if ([searchText isEqual:#""])
{
self.searching=NO;
}
[self.tableView reloadData];
}
I believe NSPredicates are good way to search in arrays.. You can refer to this link.. Using NSPredicate to filter an NSArray based on NSDictionary keys
Hi any kind souls out there,
I keep getting this error when i am click any value on the keyboard... I can run my codes but get this error when i want to do a search...
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM rangeOfString:options:]: unrecognized selector sent to instance 0x4e2a830'
*** Call stack at first throw:
Please help this noob here.. I am at end wits... =(
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *patients in listOfItems)
{
NSArray *array = [patients objectForKey:#"Patients"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
The objects in your search array are NSArray objects, this means that they do not respond to the selector rangeOfString: as that is a NSString method
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
[copyListOfItems addObject:sTemp];
}
should be something like:
for(NSArray *array in searchArray)
{
// NSString *str = [array objectAtIndex:0];
PatientInfoObject *obj = [array objectAtIndex:0];
NSString *str = obj.id;
// to be sure
if( [str isKindOfClass:[NSString class]] )
{
NSRange titleResultsRange = [str rangeOfString:searchText options:NSCaseInsensitiveCompare];
if( titleResultsRange.length != 0 )
{
[copyListOfItems addObject:str];
}
}
else
{
// this shouldn't have happened, log something to console
NSLog(#"**Object in array is not of type NSString**");
}
}
You are adding array object in your searchArray.
your app is getting crash NSString *sTemp in searchArray here because sTemp contains NSArray object not NSString object.
I've created a UITableView with a search bar. When first accessing the TableView and searching everything works fine. The problem arises when the view unloads and you go back to the search option and try to search again.
- (void)viewDidLoad {
[super viewDidLoad];
self.listContent = [[NSMutableArray alloc] initWithCapacity:20];
self.filteredListContent = [NSMutableArray arrayWithCapacity:[listContent count]];
...
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/*
Search the main list for buildings whose name match searchText; add items that match to the filtered array.
*/
for (NSArray*rows in self.listContent)
{
for (NSDictionary *row in rows)
{
NSString *locationName = [row objectForKey:#"Name"];
// TODO: BUG - *** -[CFString rangeOfString:options:]: message sent to deallocated instance 0xbe253f0
NSRange titleResultsRange = [locationName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
[filteredListContent addObject:row];
}
}
}
}
-(void) locationsReceived:(NSData *)data {
NSString *jsonData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// Create a dictionary from the JSON string
NSArray *items = [[[jsonData JSONValue] objectForKey:#"ResultSet"] objectForKey:#"Location"];
// Create a dictionary from the JSON string
[listContent release];
listContent = nil;
self.listContent = [[NSMutableArray alloc] initWithCapacity:20];
for (NSDictionary *section in sectionTitles) {
NSMutableArray *rows = [[NSMutableArray alloc] initWithCapacity:20];
[self.listContent addObject:rows];
for (NSDictionary *item in items) {
NSInteger sectionCampus = [[section objectForKey:#"CampusID"] intValue];
NSInteger rowCampus = [[item objectForKey:#"CampusID"] intValue];
if (sectionCampus == rowCampus ) {
//NSDictionary *newDic = [[NSDictionary alloc] initWithDictionary:item copyItems:YES];
//[rows addObject:newDic ];
//[newDic release];
[rows addObject:item ];
} else {
break;
}
}
}
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
/*
Update the filtered array based on the search text and scope.
*/
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/*
Search the main list for buildings whose name matches searchText; add items that match to the filtered array.
*/
for (NSArray*rows in listContent)
{
for (NSDictionary *row in rows)
{
NSString *locationName = [row objectForKey:#"Name"];
// TODO: BUG - *** -[CFString rangeOfString:options:]: message sent to deallocated instance 0xbe253f0
NSRange titleResultsRange = [locationName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
[filteredListContent addObject:row];
}
}
}
}
I would rather empty the existing listContent in -(void) locationsReceived:(NSData *)data instead of allocating a new one.
I have the following situation where
I have an NSMutableArray filled with an xml file which I want to search.
When I enter something in the search field I get this Error:
-[NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x5b388b0
What does it means and how can I fix it??
I suppose the error is somewhere around here.
- (void)searchTableView{
searchedList = [[NSMutableArray alloc] init];
NSLog(#"new list %#", searchedList);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in list) {
NSArray *array = [dictionary objectForKey:#"TITLE"];
[searchArray addObjectsFromArray:array];
}
for (NSString *TempArray in searchArray) {
NSRange titleResults = [TempArray rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResults.length > 0)
[searchedList addObject:TempArray];
}
[searchArray release];
searchArray = nil;
}
it means you are calling a method designed for an NSArray (countByEnumeratingWithState:objects:count on a NSString.
I don't know ifthis code is copy/paste from yours, but if so, at the end where you use [searchList addObject:TempArray] you don't have an object named searchList.
Also, work on your naming conventions. big time.