How to Fetch the Urdu language Words from plist? - iphone

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

Related

Having Problems With UISearchBar in UITableViewController

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

Obj-C, iOS, How do I sort by value and not key, sortedArrayUsingSelector, currently #selector(compare:)]

I need to sort by value instead of Key, I think....
Heres where I populate my arrarys
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
while(sqlite3_step(statementTMP) == SQLITE_ROW)
{
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
NSArray *arr=[[NSArray alloc]initWithObjects:category,nil];
[arrayTmp setObject:arr forKey:[NSString stringWithFormat:#"%i",cid]];
[self.cidList addObject:[NSString stringWithFormat:#"%i",cid]];
[category release];
[arr release];
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
self.allCategories = arrayTmp;
[arrayTmp release];
Heres the method where the arrays are re-sorted.
- (void)resetSearch {
NSMutableDictionary *allCategoriesCopy = [self.allCategories mutableDeepCopy];
self.Categories = allCategoriesCopy;
[allCategoriesCopy release];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
[keyArray addObject:UITableViewIndexSearch];
[keyArray addObjectsFromArray:[[self.allCategories allKeys]
sortedArrayUsingSelector:#selector(compare:)]];
self.keys = keyArray;
[keyArray release];
}
This is a problem i've had for some time, last time I looked at this I could find an altervative to sortedArrayUsingSelector compare?
EDIT
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [Categories objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SectionsTableIdentifier ];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier: SectionsTableIdentifier ] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [Categories objectForKey:key];
NSLog(#"the selected cid is = %i",[key intValue]);
selectButton.enabled = YES;
}
Anyone?
Your obviously attempting to construct an array for use in the -[UITableviewDatasource sectionIndexTitlesForTableView:]. As such, you need an array that looks like this (pseudo-code):
[UITableViewIndexSearch, 0_sectionTitle, 1_sectionTitle, 2_sectionTitle, ...]
I think your immediate problem is that you try to add the UITableViewIndexSearch string constant to the array before you sort which makes it impossible for it end up as the first element unless all your other elements sort below U.
The fix is simple, just add the constant after the sort. You can clean the code up while you're at it:
NSMutableArray *secIdx=[NSMutableArray arrayWithCapacity:[[self.allCategories allKeys] count]];
[secIdx addObjectsFromArray:[self.allCategories allKeys]];
[secIdx sortUsingSelector:#selector(compare:)];
[secIdx insertObject:UITableViewIndexSearch atIndex:0];
self.keys=secIdx;
Note that secIdx is autoreleased so you don't have to release it.
Aside from this problem, your code has a lot of unnecessary/dangerous elements that will make your app fragile and hard to maintain.
You are using a lot of init for objects that you could use autoreleased convenience methods for. The 'init`s poise the risk of memory leaks but give you no advantage.
You need to wrap scalar values in objects so they can be easily managed in collections.
You are using an unnecessary array.
You can rewrite the first block like so:
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
NSNumber *cidNum; //... move variable declerations outside of loop
NSString *category; //.. so they are not continously recreated
[self.allCategories removeAllObjects]; //... clears the mutable dictionary instead of replacing it
while(sqlite3_step(statementTMP) == SQLITE_ROW){
cidNum=[NSNumber numberWithInt:(sqlite3_column_int(statementTMP, 0))];
category=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
//... adding the autoreleased category and cidNum to array/dictionary automatically retains them
[self.allCategories addObject:category forKey:cidNum];
[self.cidList addObject:cidNum];
//[category release]; ... no longer needed
//[arr release]; ... no longer needed
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
//self.allCategories = arrayTmp; ... no longer needed
//[arrayTmp release]; ... no longer needed
Use -sortedArrayUsingComparator: (or -sortedArrayUsingFunction:context: if you can't use blocks). Example:
NSDictionary *categories = [self allCategories];
NSArray *keysSortedByValue = [[categories allKeys] sortedArrayUsingComparator:
^(id left, id right) {
id lval = [categories objectForKey:left];
id rval = [categories objectForKey:right];
return [lval compare:rval];
}];
You could make a small model class Category and implement compare inside of it, then sort an array of those objects using that compare:.
Here's some info - How to sort an NSMutableArray with custom objects in it?
Perhaps you're looking for NSSortDescriptor (and the corresponding sort method, -[NSArray sortedArrayUsingDescriptors]) and friends?
If I understood correctly then what you wish to do to get categories from database & display it on a tableView with alphabetical sorting, index on right & search bar on top. Ideally, you would like to display the Contacts application kind of a view. If that's correct, use below code for fetching items from DB & rebuilding (or resetting) it -
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
NSMutableArray *arrayTmp = [[NSMutableArray alloc] init];
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
while(sqlite3_step(statementTMP) == SQLITE_ROW) {
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:category forKey:#"Category"];
[dict setObject:[NSNumber numberWithInt:cid] forKey:#"CID"];
[arrayTmp addObject:dict];
[dict release];
[category release];
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
self.allCategories = arrayTmp;
[arrayTmp release];
And then rebuild the items using this function -
- (void)rebuildItems {
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (int i = 0; i < allCategories.count; i++) {
NSString *name = [[allCategories objectAtIndex:i] objectForKey:#"Category"];
NSString *letter = [name substringToIndex:1];
letter = [letter uppercaseString];
if (isdigit([letter characterAtIndex:0]))
letter = #"#";
NSMutableArray *section = [map objectForKey:letter];
if (!section) {
section = [NSMutableArray array];
[map setObject:section forKey:letter];
}
[section addObject:[allCategories objectAtIndex:i]];
}
[_items release];
_items = [[NSMutableArray alloc] init];
[_sections release];
_sections = [[NSMutableArray alloc] init];
NSArray* letters = [map.allKeys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
for (NSString* letter in letters) {
NSArray* items = [map objectForKey:letter];
[_sections addObject:letter];
[_items addObject:items];
}
}
Now, displaying items in tableView, use below methods -
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
if (_sections.count)
return _sections.count;
else
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString *)title
atIndex:(NSInteger)index {
if (tableView.tableHeaderView) {
if (index == 0) {
[tableView scrollRectToVisible:tableView.tableHeaderView.bounds animated:NO];
return -1;
}
}
NSString* letter = [title substringToIndex:1];
NSInteger sectionCount = [tableView numberOfSections];
for (NSInteger i = 0; i < sectionCount; i++) {
NSString* section = [tableView.dataSource tableView:tableView titleForHeaderInSection:i];
if ([section hasPrefix:letter]) {
return i;
}
}
if (index >= sectionCount) {
return sectionCount-1;
} else {
return index;
}
}
- (NSArray*)lettersForSectionsWithSearch:(BOOL)withSearch withCount:(BOOL)withCount {
if (isSearching)
return nil;
if (_sections.count) {
NSMutableArray* titles = [NSMutableArray array];
if (withSearch) {
[titles addObject:UITableViewIndexSearch];
}
for (NSString* label in _sections) {
if (label.length) {
NSString* letter = [label substringToIndex:1];
[titles addObject:letter];
}
}
if (withCount) {
[titles addObject:#"#"];
}
return titles;
} else {
return nil;
}
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self lettersForSectionsWithSearch:YES withCount:NO];
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
if (_sections.count) {
NSArray* items = [_items objectAtIndex:section];
return items.count;
} else {
return _items.count;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (_sections.count)
return [_sections objectAtIndex:section];
return nil;
}
- (id)tableView:(UITableView *)tableView objectForRowAtIndexPath:(NSIndexPath *)indexPath {
if (_sections.count) {
NSArray *section = [_items objectAtIndex:indexPath.section];
return [section objectAtIndex:indexPath.row];
} else {
return [_items objectAtIndex:indexPath.row];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create your UITableViewCell.
// Configure the cell.
NSDictionary *dict = [self tableView:tableView objectForRowAtIndexPath:indexPath];
cell.textLabel.text = [dict objectForKey:#"Category"];
cell.detailTextLabel.text = [NSString stringWithFormat:%d, [[dict objectForKey:#"CID"] intValue]];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (isSearching)
return nil;
NSString *title = #"";
if (_sections.count) {
title = [[_sections objectAtIndex:section] substringToIndex:1];
} else {
return nil;
}
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
view.backgroundColor = [UIColor colorWithRed:(58/255.0) green:(27/255.0) blue:(6/255.0) alpha:1.0];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 1, 50, 18)];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:17.0];
label.text = title;
[view addSubview:label];
[label release];
return [view autorelease];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = [self tableView:tableView objectForRowAtIndexPath:indexPath];
NSLog(#"selected row id:%d, name:%#", [dict objectForKey:#"Category"], [[dict objectForKey:#"CID"] intValue]);
}
The rest part is implementing the UISearchBarDelegate and implementing searching of tableView which can be done using below code:
- (void)searchBar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText {
[_sections removeAllObjects];
[_items removeAllObjects];
if([searchText isEqualToString:#""] || searchText == nil) {
[self rebuildItems];
return;
}
NSInteger counter = 0;
for(NSDictionary *dict in allCategories) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRange r = [[dict objectForKey:#"Category"] rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound) {
if(r.location == 0) {
[_items addObject:dict];
}
}
counter++;
[pool release];
}
[contactList reloadData];
}
Hope this is what you're looking for.
On your sorting function u should try this:
NSArray *cntxt; //im not sure this is the correct type that ur using on keyArray
[keyArray addObjectsFromArray:[self.allCategories allKeys]];
[keyArray sortUsingFunction:compareFunction context:cntxt];
And the compare function you modify to your needs
NSInteger compareFunction(id x, id y, void *context) {
//NSArray *ctxt = context;
NSArray *c1 = x;
NSArray *c2 = y;
if ([c1 value] < [c2 value])
return NSOrderedDescending;
else if ([c1 value] > [c2 value])
return NSOrderedAscending;
else
return NSOrderedSame;
}
Edit: After reading your comments and after relooking at your code, it seems like that your keyArray as objects of the type NSString, so you should change:
NSInteger compareFunction(id x, id y, void *context) {
//NSString *ctxt = context;
NSString *c1 = x;
NSString *c2 = y;
NSComparisonResult result;
result = [c1 compare:c2];
if (result<0)
return NSOrderedAscending;
else if (result>0)
return NSOrderedDescending;
else
return NSOrderedSame;
}

Obj-C, iOS, can someone explain this NSMutableArray code and suggest how I can sort on the name?

Can someone exlain this code in detail and suggest how I can sort on the name?
- (void)handleSearchForTerm:(NSString *)searchTerm {
selectButton.enabled = NO;
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in self.keys) {
NSMutableArray *array = [Categories valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in array) {
if ([name rangeOfString:searchTerm
options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.keys removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[table reloadData];
}
- (void)handleSearchForTerm:(NSString *)searchTerm {
selectButton.enabled = NO;
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init]; //creating an mutable array, which can be altered in progress.
[self resetSearch]; //calling some other method not displayed in the code here
for (NSString *key in self.keys) { //for each key,
NSMutableArray *array = [Categories valueForKey:key]; //you get the key's category
NSMutableArray *toRemove = [[NSMutableArray alloc] init]; //and initialize the array for items you wish to remove
for (NSString *name in array) { //then, for each name
if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
//you check if the name is in range of the searchterm, with which you call this function
//if you don't find it, you add it to the removal list
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key]; //if you haven't found any name, it means you've added all the names in the toRemove array
[array removeObjectsInArray:toRemove]; //that means the count of both arrays are the same
[toRemove release]; //so you remove that section entirely, since there is no result there
}
[self.keys removeObjectsInArray:sectionsToRemove]; //you remove all the keys which aren't found
[sectionsToRemove release]; //leaving you the keys which are found
[table reloadData]; //you reload the table with the found results only
}
I hope it all made sense, I did my best commenting it ;)
Good luck.

iPhone/iPad - Problem with Copy values of NSArray into NSMutableArray?

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.

*** -[CFString rangeOfString:options:]: message sent to deallocated instance 0xbe253f0

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.