How to save selected rows from UITableview to NSString variable? - iphone

I am new to xcode and making my first iPhone app.
I have a UITableview with 8 rows in a tabbed screen. I have a code which let's the user select maximum 4 rows at a time and mark it with checks when selected.
Now, when I change the view and navigate to the next tab I want to save the text from these checked rows in a single NSString variable separated by commas.
Is it possible to do so? Thank you, any help is very much appreciated.
Here is the code of the first tab from where I want to save the selected rows.
#implementation Psychological
static int count = 0;
- (void)viewDidLoad {
[super viewDidLoad];
listOfItems = [[NSMutableArray alloc] init];
[listOfItems addObject:#"1 option"];
[listOfItems addObject:#"2 option"];
[listOfItems addObject:#"3 option"];
[listOfItems addObject:#"4 option"];
[listOfItems addObject:#"5 option"];
[listOfItems addObject:#"6 option"];
[listOfItems addObject:#"7 option"];
[listOfItems addObject:#"8 option"];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [listOfItems count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.text = cellValue;
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
if(count < 4)
{
[selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
[selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];
count++;
}
} else {
[selectedCell setAccessoryType:UITableViewCellAccessoryNone];
[selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];
count --;
}
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)dealloc {
[listOfItems release];
[super dealloc];
}
#end

the easiest way is make method wich will return string that you need. Method will look something like this:
- (NSString *) selectedItems {
NSMutableString *result = [NSMutableString string];
for (int i = 0; i < [itemsArray count]; i++) {
NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
[tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
[result appendFormat:#"%#",cell.textLabel.text];
}
}
if (result.length > 2) {
[result replaceCharactersInRange:NSMakeRange(result.length-1, 1) withString:#""];
}
return result;
}
To get this line in another view controller you should find Psychological view controller in navigationController.viewController and call this method.
- (void) method {
for (UIViewController *vc in self.navigationController.viewControllers) {
if ([vc isKindOfClass:[Psychological class]]) {
NSString *str = vc.selectedItems;
}
}
}

Hope the following code suits your requirement:
//didSelect method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
if(count < 4) {
[selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
[selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];
count++;
}
} else {
[selectedCell setAccessoryType:UITableViewCellAccessoryNone];
[selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];
count --;
}
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
Declare the selectedCell globally to access in all tabs
NSMutableString *selectedCell = [[NSMutableString alloc]init]; //Should declare this string globally
//Use the following code in -viewWillDisappear Method or where you feel it fits (method that called when navigating from present class)
for(int i = 0; i < [selectedIndexes count]; i++){
[selectedCell appendString:[selectedIndexes objectAtIndex:i];
[selectedCell appendString:#","];
}
NSRange range = {[selectedCell length]-1,1};
[selectedCell deleteCharactersInRange:range];

NSMutableString *selectedRow=[NSMutableString alloc]init];
for(int i=0; i<[count];i++)
{
selectedRow=[arrayName objectAtIndex:row];
[selectedRow appendString:#","];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if (selectedCell.accessoryType == UITableViewCellAccessoryNone) {
if(count<4){
selectedCell.accessoryType = UITableViewCellAccessoryCheckmark;
[[listOfItems objectAtIndex:indexPath.row]setObject:#"YES" forKey:#"Selected"];
count++;
}
} else if (selectedCell.accessoryType == UITableViewCellAccessoryCheckmark) {
if(count>=0){
selectedCell.accessoryType = UITableViewCellAccessoryNone;
[[listOfItems objectAtIndex:indexPath.row]setObject:#"NO" forKey:#"Selected"];
count--;
}
}
replace above code and when you want to navigate your page at that time check whether Selected value yes or no if yes then pass that value otherwise leave it.
for (int i =0 ; i<[listOfItems count]; i++) {
if ([[[listOfItems objectAtIndex:i]valueForKey:#"Selected"]isEqualToString:#"YES"]) {
if ([selectedId length]==0) {
selectedId = [NSString stringWithFormat:#"%#",[[listOfItems objectAtIndex:i]valueForKey:#"user_id"]];
}else {
selectedId = [selectedId stringByAppendingFormat:#",%#",[[listOfItems objectAtIndex:i]valueForKey:#"user_id"]];
}
}
}

You may want to have a global array.
Store the selected values into that global array then it would be easy to display them elsewhere.. :-)

Create a new class, let's call it Option, and give it two properties. One is a NSString called name and the other is a BOOL called selected. Instead of having listOfItems as an array of strings, make it a list of Option objects. Have each Option keep track of whether or not it's currently selected.
Make the controller class that owns listOfItems into a UITabBarControllerDelegate and implement tabBarController:didSelectViewController: so that it builds the string and passes it to the next selected controller.

Related

Accordion style tableview without using sections

I am interning for the summer on an iOS native app development team. They gave me a task of accomplishing removing/inserting cells in a tableview without using sections. I am struggling with the task if anyone could take a look at the code and try to help me out id be much appreciated. I am getting some removals and disappearances but it is not staying consistent, and it is adding cells that are already visible. (consistency in the sense that once i insert rows, row 3 is now row 5, and my modulo arithmetic gets thrown off.
I am very new to objective c so any advice / help would be much appreciated.
#implementation MasterViewController
NSMutableArray * levels;
NSMutableArray * array;
NSMutableIndexSet * expandedSections;
NSMutableDictionary * dict;
-(BOOL) loadFiles{
// NSFileManager * fileManager = [NSFileManager defaultManager];
if (!expandedSections) {
expandedSections = [[NSMutableIndexSet alloc]init];
}
array = [[NSMutableArray alloc]init];
levels = [[NSMutableArray alloc]init];
for (int i=0; i<20; i++) {
NSString * temp = [[NSString alloc]initWithFormat:#"This is row : %i ", i];
[array addObject:temp];
}
for (int i=0; i<20; i++) {
NSNumber * temp = [[NSNumber alloc]initWithInt:i];
[levels addObject:temp];
}
dict = [[NSMutableDictionary alloc]initWithObjects:array forKeys:levels];
NSLog(#"TEST: %#", [dict objectForKey:[levels objectAtIndex:1]]);
return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Master", #"Master");
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadFiles];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([expandedSections containsIndex:section]) {
return [array count] +2;
}
return [array count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (!(indexPath.row %3)==0) {
cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]];
[cell setIndentationLevel:2];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
} else {
cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]];
[cell setIndentationLevel:0];
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (!self.detailViewController) {
self.detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
}
BOOL currentlyExpanded = [expandedSections containsIndex:indexPath.row];
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(#"CurrentlyExpanded : %d", currentlyExpanded);
NSLog(#"TEST: %#", [dict objectForKey:[levels objectAtIndex:indexPath.row ]]);
if ((indexPath.row %3)==0) {
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded) {
rows = 2;
[expandedSections removeIndex:section];
} else {
[expandedSections addIndex:section];
rows = 2;
}
for (int i=indexPath.row+1; i<=(indexPath.row + rows); i++) {
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
if (currentlyExpanded) {
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
} else {
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
if ((indexPath.row %3)>0) {
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
}
#end
Take a look at TLIndexPathTools. It greatly simplifies building dynamic tables like this. It does all the work calculating and performing the batch updates for you. Try running the Outline sample project. It demonstrates how to build an expandable tree without using sections. You can accomplish what you need by just building up a two-level tree.

Searching a UITableview

I am trying to do a search in a UITableview. I have implemented the UISearchDisplayDelegate, UISearchBarDelegate method at the correct way. This is how my cellForRowAtIndexPath looks like.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView){
Contact *contact = [self.filteredListContent objectAtIndex:indexPath.row];
NSString *text = [NSString stringWithFormat:#"%# %#",contact.name,contact.firstName];
NSLog(#"CellForRowAtIndexPath contact text is %#",text);
cell.textLabel.text = text;
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}else{
NSString *alphabet = [firstIndex objectAtIndex:[indexPath section]];
//---get all states beginning with the letter---
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF.name beginswith[c] %#",alphabet];
NSArray *contacts = [listContent filteredArrayUsingPredicate:predicate];
Contact *contact = [contacts objectAtIndex:indexPath.row];
NSString *text = [NSString stringWithFormat:#"%# %#",contact.name,contact.firstName];
cell.textLabel.text = text;
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
return cell;
}
And this is my filterContentForSearchText method
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
for (Contact *contact in listContent)
{
NSString *searchString = [NSString stringWithFormat:#"%# %#",contact.name,contact.firstName];
NSRange range = [searchString rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[self.filteredListContent addObject:contact];
[self.searchDisplayController.searchResultsTableView reloadData];
}
}
}
The strange thing is. In my cellForRowAtIndexPath it returns me the correct data. But the tableview itselfs keeps given me the NO RESULTS label.
Any help with this?
Follow this tutorial how-to-add-search-bar-uitableview ..
Just see the method cellForRowAtIndexPath: in which how to set the search array when user searched record from UISearchBar...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"RecipeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
}
return cell;
}
Use an array to show data in table(showDataArray)
Use an array to store all input values(dataArray)
Use showDataArray to populate your table always
In the searchfield when charecter range changes call a method to filter the data using predicate from dataArray
Save the value to showDataArray
Call for table reloadData
First add UISearchBar on top of UITabelView documentation
And then Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,
self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:#"YorArrayList", nil]; // array no - 2
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
And Write following delegate Method of UISearchBar
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText
{
NSString *name = #"";
NSString *firstLetter = #"";
if (self.listOfTemArray.count > 0)
[self.listOfTemArray removeAllObjects];
if ([searchText length] > 0)
{
for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
{
name = [self.ItemOfMainArray objectAtIndex:i];
if (name.length >= searchText.length)
{
firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
//NSLog(#"%#",firstLetter);
if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
{
// strings are equal except for possibly case
[self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
NSLog(#"=========> %#",self.listOfTemArray);
}
}
}
}
else
{
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
}
[self.tblView reloadData];
}
And Write in cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Foobar"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Foobar"];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.textColor = [UIColor blackColor];
}
cell.textLabel.text = [self.listOfTemArray objectAtIndex: indexPath.row];
return cell;
}

Plist Search of Tableview

I have Plist which is been populated on the tableview with expanded sections ..now i want to search the table..below in images you can see what is happening when I search anything.
.
just because I am searching it but need some changes in the cellforrowatindexpath for search results....
please check the code and let me know what to do for searching plist..
what should be changes for the cellforrowatindexpath and noofrowsinsection for search from plist
.
.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.mySections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = 0;
if ([self tableView:tableView canCollapseSection:section] || !(tableView == self.searchDisplayController.searchResultsTableView) )
{
if ([expandedSections containsIndex:section] )
{
NSString *key = [self.mySections objectAtIndex:section];
NSArray *dataInSection = [[self.myData objectForKey:key] objectAtIndex:0];
return [dataInSection count];
}
return 1;
} else if(tableView == self.searchDisplayController.searchResultsTableView) {
rows = [self.searchResults count];
return rows;
}
return 1;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
NSString *key = [self.mySections objectAtIndex:section];
return [NSString stringWithFormat:#"%#", key];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//some changes required to display plst
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
}
// Configure the cell...
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}else {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [self.mySections objectAtIndex:section];
NSDictionary *dataForSection = [[self.myData objectForKey:key] objectAtIndex:0];
NSArray *array=dataForSection.allKeys;
cell.textLabel.text = [[dataForSection allKeys] objectAtIndex:row];
cell.detailTextLabel.text=[dataForSection valueForKey:[array objectAtIndex:indexPath.row]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
}
}
}
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
self.searchResults = [self.mySections filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
UISearchBar * searchBar = [controller searchBar];
[self filterContentForSearchText:searchString scope:[[searchBar scopeButtonTitles] objectAtIndex:[searchBar selectedScopeButtonIndex]]];
return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
UISearchBar * searchBar = [controller searchBar];
[self filterContentForSearchText:[searchBar text] scope:[[searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
The search results you are using in numberOfRows should be used for numberOfSections
Since you are filtering for section title and not rows.

UITableView: use object from dictionary as title on detail view

I have the following code to make a table from string turned into a dictionary:
- (void)viewDidLoad {
[super viewDidLoad];
testArray = [[NSArray alloc] init];
NSString *testString = #"Sam|26,Hannah|22,Adam|30,Carlie|32";
testArray = [testString componentsSeparatedByString:#","];
dict = [NSMutableDictionary dictionary];
for (NSString *s in testArray) {
testArray2 = [s componentsSeparatedByString:#"|"];
[dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
if (testArray.count >indexPath.row) {
cell.textLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]];
cell.detailTextLabel.text = [dict objectForKey:cell.textLabel.text];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
What I would like is for the selected row title to be set as the title on my detail view.
I tried with:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:self.detailController animated:YES];
}
But I get an "EXC_BAD_ACCESS" error.
It works fine if I use #"1" as title, it's just something with my dictionary call that's wrong, I assume.
Make dict a retained dictionary instead of an autoreleased one.
I.E. declare it maybe like this:
dict = [[NSMutableDictionary alloc] initWithCapacity: [testArray count]];
in your viewDidLoad method. Make sure to release it when viewDidUnload is called.
Also, make sure of the number of keys in your dict before calling:
self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]];
So, I would do:
if(dict && ([[dict allKeys] count] > [indexPath row])
{
self.detailController.title =
[[dict allKeys] objectAtIndex:[indexPath row]];
} else {
self.detailController.title = #"Here's a problem";
}
Did you implement these UITableView delegate methods ? All these are needed. Also can you post more detailed StackTrace.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [resultSet count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 280.0;
}

Not able to access array with ids in another view controller in iphone

these is some code from my project..
for (index=0; index<[feed count]; index++) {
//NSLog(#"........%#",[feed objectAtIndex:2]);
NSString* forName=[feed objectAtIndex:index];
NSString *nameString = [forName valueForKey:#"name"];
NSLog(#"--------%#",nameString);
[nameArray addObject:nameString];
NSString *idString = [forName valueForKey:#"id"];
NSLog(#"--------%#",idString);
[idArray addObject:idString];
}
MyFriends *detailViewController = [[MyFriends alloc] initWithNibName:#"MyFriends" bundle:nil];
// ...
// Pass the selected object to the new view controller.
detailViewController.fbNames=nameArray;
detailViewController.fbIds=idArray;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
My problem is in another controller when I am accessing array with names which is fbNames in another class it is showing me proper names,But when I am accessing fbIds which is the array with Ids ...they are showing me null..
how to correct this?
here...in this class ...fbNames are working fbIds are not..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [fbNames count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text=[fbNames objectAtIndex:indexPath.row];
NSLog(#"%#",cell.textLabel.text);
return cell;
}
NSString* forName=[feed objectAtIndex:index];
NSString *nameString = [forName valueForKey:#"name"];
I don't think NSString has valueForKey: