Dealing with editable items in a filtered UITable with an NSMutableArray copy - iphone

I have a UITable with a datasource that is set to a 'copy' of the original data. I use this copy to displayed filtered results (either 'All' or only those that are 'checked' with a UISwitch in each row). My logic for doing the filtering is here:
-(void)filterItems {
[tableData removeAllObjects];
if (checkedOrNotSwitch.selectedSegmentIndex == 0) {
[tableData addObjectsFromArray:self.defaultChecklistItemsArray];
} else {
for (NSMutableDictionary *sectionDict in self.defaultChecklistItemsArray) {
NSMutableArray *newItemsArray = [[NSMutableArray alloc] init];
[newItemsArray removeAllObjects];
for (NSMutableDictionary *itemDict in [sectionDict objectForKey:#"categoryItems"]) {
if ([[itemDict objectForKey:#"isComplete"] boolValue]) {
[newItemsArray addObject:itemDict];
}
}
if ([newItemsArray count] > 0) {
NSMutableDictionary *newSectionDict = [[NSMutableDictionary alloc] initWithDictionary:sectionDict];
[newSectionDict setObject:newItemsArray forKey:#"categoryItems"];
[tableData addObject:newSectionDict];
[newSectionDict release];
}
}
}
[checklistTable reloadData];
}
The filtering itself now works correctly. In my custom cell, each row has a UISwitch. The switch runs this function when its changed:
-(IBAction) switchValueChanged{
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
[self.parentController updateCompletedStatusAtIndexPath:indexPath toStatus:isCompleted.on];
}
The function above is in the class for the tableviewcell itself. The function I call in the superview is this:
-(void)updateCompletedStatusAtIndexPath:(NSIndexPath *)indexPath toStatus:(BOOL)status{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSMutableDictionary *currentsection = [[NSMutableDictionary alloc] initWithDictionary:[tableData objectAtIndex:section]];
NSMutableArray *itemsArray = [[NSMutableArray alloc] initWithArray:[currentsection objectForKey:#"categoryItems"] copyItems:YES];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:[itemsArray objectAtIndex:row]];
NSLog(#"BOOL = %#\n", (status ? #"YES" : #"NO"));
[tempDict setValue:[NSNumber numberWithBool:status] forKey:#"isComplete"];
[itemsArray replaceObjectAtIndex:row withObject:tempDict];
[currentsection setValue:itemsArray forKey:#"categoryItems"];
[tableData replaceObjectAtIndex:section withObject:currentsection];
[tempDict release];
[itemsArray release];
[currentsection release];
[checklistTable reloadData];
}
Before I implemented the filtering and used the logic above on self.defaultChecklistItemsArray directly, it worked and saved the data when the switch was flipped.
Now when I first enter the app, it loads the array of data from nsuserdefaults. I navigate to the view with the table and it displays the data correctly there with the UISwitches all in the correct position given the data (some on, some off). When I tap one of the switches, then click the segmentedcontrol that does the filtering, the data reverts back to the state it was loaded in, implying that the flipping of the switch did not actually effect the data at all (even though I don't think I did a deep copy anywhere here so I figured it should be doing the right thing). Any suggestions?

Related

Sort NSArray with NSPredicate then store in a new array

I have a UITableView that gets populated via an array (tableArray), who gets populated from core data.
each UITableViewCell gets assigned a number at creation time and the numbers are stored in an array. (numberArray)
when the user reorders the rows, the numbers get moved around in the array (in conjunction with the tableView of course)
So two Mutable arrays are used here.
The numberArray holds the numbers (or the order) of the TableViewCells.
I need to sort the array that holds the UITableViewCell's text (tableArray)
to reflect the same order that the numberArray holds.
Also, this is important: as i said before, each cell gets assigned a number, this number is stored in the numberArray,
I need both of the arrays to be sorted to hold the same values in the same place.
So for example:
tableArray hold some objects:
1) hi
2) whats Up
3) this
4) is cool!
so as you can see each object here was assigned a number 1-4.
and each of these numbers is added to the numberArray.
The user can move the cells around so obviously the order of the numbers will change.
So when the view loads up, i need to get the exact order of the numberArray whether it is
1,2,3,4 or 2,4,3,1
and i need to sort the tableArray to reflect the same order as the numberArray
so when the view loads up, if the numberArray's order is 2,3,4,1 i want the tableArray's order to be set to
2"whats up", 3"this", 4"is cool!", 1"hi".
I believe i can do this via NSPredicate.
Any help is greatly appreciated!
EDIT
cellForRow:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * identifier = #"identifier";
self.myCell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (self.myCell == nil) {
self.myCell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
HandgunAmmo *handgunAmmo = [self.tableArray objectAtIndex:indexPath.row];
self.myCell.brandLabel.text = handgunAmmo.brand;
self.myCell.caliberLabel.text = handgunAmmo.caliber;
self.myCell.numberOfRoundsLabel.text = handgunAmmo.numberOfRounds;
return self.myCell;
}
And in my viewWIllAppear method:
-(void)viewWillAppear:(BOOL)animated{
if (self.context == nil)
{
self.context = [(RootAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"HandgunAmmo" inManagedObjectContext:self.context];
[request setEntity:entity];
NSError *error;
NSMutableArray *array = [[self.context executeFetchRequest:request error:&error] mutableCopy];
[self setTableArray:array];
[self.ammoTable reloadData];
[super viewWillAppear:YES];
}
So, the reason why the array doesnt stay persistent when being changed is because im loading the data from core data, and i call [self setTableArray:array]; which reloads all of the data from core data into the array, then it populates the tableview with the array. So i need to be able to sort the array before i set it equal to self.tableArray.
Thank you for the help!
Why don't you leave the tableArray unchanged, and use the numberArray as an index into the other array.
You would initialize the numberArray to 0, 1, 2, ..., n-1 with
numberArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [tableArray count]; i++) {
[numberArray addObject:[NSNumber numberWithUnsignedInteger:i]];
}
When you need an item, e.g. in cellForRowAtIndexPath, you access it via the index:
NSUInteger i = [[numberArray objectAtIndex:row] unsignedIntegerValue];
NSString *item = [tableArray objectAtIndex:i];
Now you need to reorder the numberArray only, and the changes will automatically be reflected in the table view.
Update: A good solution to handle the reordering of Core Data objects in a table view can be found here: UITableView Core Data reordering
I cant see a way to solve it with a predicate
NSArray *stringArray = #[#"hi", #"what's up?", #"this", #"is cool"];
NSArray *numberArray = #[#2, #4, #3, #1];
NSMutableArray *combinedArray = [NSMutableArray array];
//connect string with the numbers of there new position
[numberArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *string =stringArray[[obj integerValue]-1];
[combinedArray addObject:#[string, obj]];
}];
NSMutableArray *orderedArray = [NSMutableArray array];
[combinedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[orderedArray addObject:obj[0]];
}];
NSLog(#"%#", orderedArray);
result
(
"what's up?",
"is cool",
this,
hi
)
NSMutableArray *unsortedArray = [NSMutableArray arrayWithObjects:#"1) hi",#"2) whats Up",#"3) this",#"4) is cool!",nil];
NSArray *guideArray = [NSArray arrayWithObjects:#"2",#"4",#"3",#"1", nil];
for(int i=0; i< [guideArray count];i++)
{
for(int j=0; j< [unsortedArray count];j++)
{
if([[[unsortedArray objectAtIndex:j] substringToIndex:[[guideArray objectAtIndex:i] length]] isEqualToString:[guideArray objectAtIndex:i]])
//if([[unsortedArray objectAtIndex:j] containsObject:[guideArray objectAtIndex:i]])
{
[unsortedArray exchangeObjectAtIndex:j withObjectAtIndex:i];
break;
}
}
}
NSLog(#"%#",unsortedArray);
OR
guideArray = #[#"2",#"4",#"3",#"1"];
unsortedArray = [#[#[#"1) hi"],
#[#"2) wats up "],
#[#"3) this,"],
#[#"4) cool"]] mutableCopy];
[unsortedArray sortUsingComparator:^(id o1, id o2) {
NSString *s1 = [o1 objectAtIndex:0];
s1 = [s1 substringToIndex:[s1 rangeOfString:#")"].location];
NSString *s2 = [o2 objectAtIndex:0];
s2 = [s2 substringToIndex:[s2 rangeOfString:#")"].location];
NSInteger idx1 = [guideArray indexOfObject:s1];
NSInteger idx2 = [guideArray indexOfObject:s2];
return idx1 - idx2;
}];
NSLog(#"%#",unsortedArray);
Try this hope this help partially.

Save and Load UISwitch state in TableView

I want to save the switch state. I created custom cell class witch print one Switch on label but there is problem that if i search some text then Table View reload and my selected switch State is going to change, Is it possible to Maintain that state ?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
....
selectionStyle = UITableViewCellSelectionStyleNone;
CfResultFatch *temp = [result objectAtIndex:indexPath.row];
NSLog(#"%#",temp.complanName);
//[cell.switchOnOff setOn:NO];
[cell.switchOnOff setTag:indexPath.row];
[cell.switchOnOff addTarget:self action:#selector(selectUser:)forControlEvents:UIControlEventValueChanged];
[cell.switchOnOff setTag:indexPath.row];
cell.lblUserName.text = temp.complanName;
cell.textFld.text = temp.cipd;
return cell;
}
//selectUser which is call when switch state change
-(IBAction)selectUser:(UISwitch*)sender{
if(sender.on)
{
[selectedpet addObject:[result objectAtIndex:sender.tag]];
}else{
NSLog(#"%#",sender);
for(int j=0;j<[selectedpet count]; j++)
{
CfResultFatch *temp = [result objectAtIndex:sender.tag];
CfResultFatch *temp1= [selectedpet objectAtIndex:j];
if([(temp.complanName)isEqualToString:(temp1.complanName)]) {
[selectedpet removeObjectAtIndex:j];
}
}
}
}
//and Search in searchBar this methode is call when search some text and the data is change from data base problem is here is i select 0 and 1 index switch on and then search some text, the new data in table view come with 0 and 1 index ON,how to maintain it and how to get my previous state of Switch
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSString *weburl = [NSString stringWithFormat:#"%#%#", #"http://192.168.1.196/ravi/searchUser.php?mname=",searchText];
NSURL *url = [NSURL URLWithString:weburl];
NSData *data =[NSData dataWithContentsOfURL:url];
[self getData:data];
[temptab reloadData];
}
And ya. sorry for my poor english
You should store the state of the UISwitch when it is changed. It might not be the best way to do this, but you could store the states in a dictionary like this:
NSMutableDictionary *states = [NSMutableDictionary alloc] init];
[states setObject:[NSNumber numberWithBool:sender.on] forKey:[NSNumber numberWithInt:sender.tag]]
Then, when showing the UITableViewCell:
if ([states objectForKey:[NSNumber numberWithInt:indexPath.row]] != nil)
cell.switchOnOff.on = [[states objectForKey:[NSNumber numberWithInt:indexPath.row]] boolValue]
else
cell.switchOnOff.on = NO;

retrieved data from sqlite database and displaying it on grouped table view

hii every one
i am brand new to obj c, i have did a sample project where i have 2 screens on the first screen i have six text fields & 2 buttons named save and ViewData ,on click of save data which is entere d in the text field will be get saved in the sqliteData Base ,& on click of the button ViewData it will navigate to a new screen which has a grouped table view, here i am trying to display the data which is stored in the sqlite ,in the grouped table view i have 6 sections i am using following code to display the data in grouped table view,problem is grouped table view is displaing only the last data which is entered ih the text field,,but i need to display all the data which enterd should be shown under that section
appDelegate = (iICS_testAppDelegate *)[[UIApplication sharedApplication] delegate];
for(int intVar=0;intVar < [appDelegate.arrObjects count];intVar++)
{
insertUpdateDelete *InsertRecord = [appDelegate.arrObjects objectAtIndex:intVar];
NSLog(#"InsertRecord:%#",InsertRecord);
NSMutableArray *arrTemp1 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strsixth,nil];
NSMutableArray *arrTemp2 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strfifth,nil];
NSMutableArray *arrTemp3 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strFourth,nil];
NSMutableArray *arrTemp4 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strLogin,nil];
NSMutableArray *arrTemp5 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strMiddleName,nil];
NSMutableArray *arrTemp6 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strFirstName,nil];
NSMutableDictionary *temp =[[NSMutableDictionary alloc]initWithObjectsAndKeys:arrTemp1,#"Item Name",arrTemp2,#"Manufacturer",arrTemp3,#"Weight of Item",arrTemp4,#"Num of Item",arrTemp5,#"Price of Item",arrTemp6,#"MFG Date",nil];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[arrTemp1 release];
[arrTemp2 release];
[arrTemp3 release];
[arrTemp4 release];
[arrTemp5 release];
[arrTemp6 release];
}
here im assigning the text for the row
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//insertUpdateDelete *InsertRecord = [appDelegate.arrObjects objectAtIndex:indexPath.row];
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
NSArray *listData =[self.tableContents objectForKey:[self.sortedKeys objectAtIndex:[indexPath section]]];
UITableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
//cell.textLabel.text = [appDelegate.arrObjects objectAtIndex:row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
thanks in advance!
This is my snapshopt of grouped table view. I need the data which is entered through the text field shoul be viewed under particular section
Solution for only the last data is displaying,
Instead of NSArray use NSMutableArray.
Solution for wrong field values,
Your problem may be in insertion itself,
NSArray *arrTemp1 = [[NSArray alloc]initWithObjects:InsertRecord.strsixth,nil];
NSArray *arrTemp2 = [[NSArray alloc]initWithObjects:InsertRecord.strfifth,nil];
You are inserting price value into date field, i think so. Please check that.
Change your code as,
NSMutableArray *arrTemp1 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp2 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp3 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp4 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp5 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp6 = [[NSMutableArray alloc]init];
for(int intVar=0;intVar < [appDelegate.arrObjects count];intVar++)
{
insertUpdateDelete *InsertRecord = [appDelegate.arrObjects objectAtIndex:intVar];
NSLog(#"InsertRecord:%#",InsertRecord);
[arrTemp1 addObject:InsertRecord.strsixth];
[arrTemp2 addObject:InsertRecord.strfifth];
[arrTemp3 addObject:InsertRecord.strFourth];
[arrTemp4 addObject:InsertRecord.strLogin];
[arrTemp5 addObject:InsertRecord.strMiddleName];
[arrTemp6 addObject:InsertRecord.strMiddleName];
}
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:arrTemp1,#"Item Name",arrTemp2,#"Manufacturer",arrTemp3,#"Weight of Item",arrTemp4,#"Num of Item",arrTemp5,#"Price of Item",arrTemp6,#"MFG Date",nil];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[arrTemp1 release];
[arrTemp2 release];
[arrTemp3 release];
[arrTemp4 release];
[arrTemp5 release];
[arrTemp6 release];

NSMutableArray, pList, Tableview muddle and meltdown

I have a preferences view which shows a different table view depending on which Segmented Control is clicked.
I hard coded some NSMutableArrays to test basic principles:
prefsIssuesList = [[NSMutableArray alloc] init];
[prefsIssuesList addObject:#"Governance"];
[prefsIssuesList addObject:#"Innovation and technology"];
...etc
prefsIndustriesList = [[NSMutableArray alloc] init];
[prefsIndustriesList addObject:#"Aerospace and defence"];
... etc
prefsServicesList = [[NSMutableArray alloc] init];
[prefsServicesList addObject:#"Audit and assurance"];
...etc
currentArray = [[NSMutableArray alloc] init];
currentArray = self.prefsIssuesList;
Then reload the tableview with currentArray, adding a UITableViewCellAccessoryCheckmark.
Everything works fine.
But now I want to store wether the checkmark is on or off in a pList file, and read this back in.
Ideally want to a plist like this
Root Dictionary
Issues Dictionary
Governance Number 1
Innovation and technology Number 0
etc
I've got as far as working this out
// Designate plist file
NSString *path = [[NSBundle mainBundle] pathForResource: #"issues" ofType:#"plist"];
// Load the file into a Dictionary
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.allNames= dict;
[dict release];
NSLog(#"Dict is %#", allNames); // All the data in the pList file
NSMutableArray *issueSection = [allNames objectForKey:#"Issues"];
NSLog(#"Issues is %#", issueSection); // The data is the Issues Section
NSString *issueVal = [issueSection objectForKey:#"Governance"];
NSLog(#"Governance is %#", issueVal); //The value of the Governance key
But what I really want to do is loop through the Issues Dictionary and get the key/value pairs so
key = cell.textLabel.text
value = UITableViewCellAccessoryCheckmark / UITableViewCellAccessoryNone
depending wether it's 1 or 0
I'm assuming that I can still assign one of the three NSMutableArrays to currentArray as I did in the hardcoded version, and use currentArray to reload the tableview.
Then amend this code to build the tableview
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [names objectForKey:key];
static NSString *CellIdentifier = #"Cell";
//UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell=[[[UITableViewCell alloc]
initWithFrame:CGRectZero
reuseIdentifier: CellIdentifier] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
But my brain has melted, I've spent about six hours today reading up on pLists, NSArrays, NSMutableDisctionaries, standardUserDefaults to little avail.
I've managed to UITableViews inside UINavigationViews, use SegmentedControls, download asynchronous XML, but now I'm finally stuck, or fried, or both. Over what should be fairly simple key/value pairs.
Anyone care to give me some idiot pointers?
Typing it out led to another post with that one little word I needed to get me back on track :)
Use key/value pairs in a pList to stipulate the name of the cell and wether it was selected or not by the user.
plist is based on a structure like this
Root Dictionary
Services Dictionary
Peaches String 1
Pumpkin String 0
Here's how I grabbed three Dictionary arrays from a pList and used the key/value pairs to reload a tableview depending on which segmentControl was touched:
- (void)viewDidLoad {
[super viewDidLoad];
// Designate plist file
NSString *path = [[NSBundle mainBundle] pathForResource: #"issues" ofType:#"plist"];
// Load the file into a Dictionary
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.allNames= dict;
[dict release];
// Create the Named Dictionaries from Dictionary in pLIst
NSMutableDictionary *allIssues = [self.allNames objectForKey:#"Issues"];
self.prefsIssuesList = allIssues;
[allIssues release];
NSMutableDictionary *allIndustries = [self.allNames objectForKey:#"Industries"];
self.prefsIndustriesList = allIndustries;
[allIndustries release];
NSMutableDictionary *allServices = [self.allNames objectForKey:#"Services"];
self.prefsServicesList = allServices;
[allServices release];
// Assign the current Dictionary to out placeholder Dictionary
currentDict = [[NSMutableDictionary alloc] init];
currentDict = self.prefsIssuesList;
}
Then styling the table cells
- (UITableViewCell *)tableView:(UITableView *)prefsTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSArray *keysArray = [self.currentDict allKeys];
NSString *theKey = [keysArray objectAtIndex:row];
NSString *theValue = [self.currentDict objectForKey: [keysArray objectAtIndex:row]];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell=[[[UITableViewCell alloc]
initWithFrame:CGRectZero
reuseIdentifier: CellIdentifier] autorelease];
}
cell.textLabel.text = theKey;
if (theValue == #"0") {
cell.accessoryType = UITableViewCellAccessoryNone;
}else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
The if clause at the end doesn't seem to be working, I'll post that as a new question (unless anyone comments quickly!)
Finally the segmentControls assign the different dictionaries to the placeholder array and reload the tableview
This took me a very long day to figure out (as a noobie) so I hope it helps someone
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
//currentArray = self.prefsIssuesList;
currentDict = self.prefsIssuesList;
break;
case 1:
//currentArray = self.prefsIndustriesList;
currentDict = self.prefsIndustriesList;
break;
case 2:
//currentArray = self.prefsServicesList;
currentDict = self.prefsServicesList;
break;
default:
//currentArray = self.prefsIssuesList;
currentDict = self.prefsIssuesList;
break;
}
[prefsTableView reloadData];
}
Shout if there's a neater or better way of d

How to implement UITableView search functionality

My iPhone application has a UITable View implemented with search functionality in it. The values in the table are grouped into sections from A-Z. Whenever a user tap on particular cell in the table it loads a detail view controller which gives all the values of that particular user. Now my problem is whenever I search some contact and tap on a particular user to check his detail view it always returns a contact starting with letter A. So, my doubt is how to implement this search functionality. Is there a way to get the name of the contact I tapped..Please check this screenshot.. For example if I search some contact starting with letter 'B' and tap on that contact it loads the detail view of a contact starting with letter 'A'. I get all the values from the database. Can you please help me out...
This is the code:
The code I wrote here is in a method:
I am getting all the contacts from database and assigning to an array contacts. Then I am grouping all the contacts according to the alphabets and grouping everything into a dictionary with keys as A-Z and values as name of contacts starting with these letters. Now when I search for a particular contact his name may start with either A ,B or Z..so in the search bar when I search for a particular contact for example a contact starting with letter Z, in this case it gives the details of a person with A. I want this to change so that whenever I tap on a particular contact it should load its details. I am unable to figure out how to do it..
contacts = [[db getContacts:#"Contacts"] componentsSeparatedByString:#","];
[db cleanup];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
NSString *charString;
for (int i=65; i<91; i++) {
charString = [NSString stringWithFormat:#"%c",(char *)i];
[tempArray addObject:charString];
}
[charString release];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0; i<[tempArray count]; i++) {
NSMutableArray *contactsByIndex = [[[NSMutableArray alloc] init]autorelease];
NSString *tempChar = [tempArray objectAtIndex:i];
for (int j=0; j<[contacts count]-1; j++)
{
NSString *test = [contacts objectAtIndex:j];
NSString *tempString = [test substringToIndex:1];
if ([tempString isEqualToString:tempChar]) {
[contactsByIndex addObject:[contacts objectAtIndex:j]];
}
}
[dict setObject:contactsByIndex forKey:[tempArray objectAtIndex:i]];
}
self.contactNames = dict;
NSArray *array = [[contactNames allKeys] sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
self.contactKeys = array;
[dict release];
[tempArray release];
//---display the searchbar---
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeYes;
listOfContacts = [[NSMutableArray alloc] init];
for (NSString *key in array)
{
NSArray *contactsArray = [contactNames objectForKey:key];
for (NSString *name in contactsArray) {
[listOfContacts addObject:name];
}
}
- (void) searchContactsTableView {
//---clears the search result---
[searchResult removeAllObjects];
for (NSString *str in listOfContacts) {
NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[searchResult addObject:str];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSString *selectedRow=nil;
if (isSearchOn) {
selectedRow=[searchResult objectAtIndex:indexPath.row];
}
DetailViewController *detailViewController;
int section_index=[indexPath indexAtPosition:[indexPath length]-2];
int sugarid_Index = [indexPath indexAtPosition: [indexPath length]-1];
NSString* sectionName=[contactKeys objectAtIndex:section_index];
NSLog(#"%#",sectionName);
//This is a method which gets the details of a particular contact based on the section and the row selected..Contacts is the table name
NSString *getContact=[db getId:#"Contacts" bySection:sectionName andIndex:sugarid_Index];
id=[db getContact:#"Contacts" id:getContact];
// Pass the selected object to the new view controller.
detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.eachContact=contactForSugarId;
[self.navigationController pushViewController:detailViewController animated:YES];
}
When I search for a contact it should search for the name in database and should return its details. Is there a way to do it..please let me know or is there a way to get the name of the cell i.e. the contact name so that I can use that in one of my database methods to retrieve the details of the contact I selected.
Off hand it sounds like you're looking in the wrong array of contacts after the search. You need to have two arrays. One with all the contacts, and one with the filtered contacts. When you search, put all the results in order in the filtered list, and pull the details from that one.
Does this make sense?
If not, try posting a bit of code, and explaining your structure.