How to perform Validation in ios uitableview (group table)? - iphone

In my app i have used UItableview group table.
In which there are two section and i want to perform validation on it.
for eg:In section 1 there are two row's,if user select row one user have to select some value from section 2 and if user have select second row in 1 section then no need of selection in section two.
following is my code:
- (void)viewDidLoad
{
NSArray *arr_data1 =[[NSArray alloc]initWithObjects:#"Yes",#"No",nil];
NSArray *arr_data2 =[[NSArray alloc] initWithObjects:#"Monotherapy",#"Adjunctive",nil];
NSDictionary *temp =[[NSDictionary alloc]
initWithObjectsAndKeys:arr_data1,#"",arr_data2,
#"Was it monotherapy or adjunctive",nil];
self.tableContents =temp;
self.arr_data =[[self.tableContents allKeys]
sortedArrayUsingSelector:#selector(compare:)];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.arr_data count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.arr_data objectAtIndex:section];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *listData =[self.tableContents objectForKey:
[self.arr_data objectAtIndex:section]];
return [listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
NSArray *listData =[self.tableContents objectForKey:
[self.arr_data objectAtIndex:[indexPath section]]];
UITableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *listData =[self.tableContents objectForKey:
[self.arr_data objectAtIndex:[indexPath section]]];
NSUInteger row = [indexPath row];
NSLog(#"fdfdfdf=%d",[indexPath row]);
NSString *rowValue = [listData objectAtIndex:row];
if ([rowValue isEqualToString:#"Yes"])
{
NSString *message = [[NSString alloc] initWithFormat:#"%#",rowValue];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"You selected"
message:message delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

In - (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath ,
you can check the section you need by using the following code:
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 0)
{
//do as per you requirement
}
else if(indexPath.section == 1)
{
//do as per you requirement
}
}

You can first declare a variable count to keep track of how many items are selected in section 2 and isItemRequired as a flag variable and sythesize them, then use these delegates:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
A sample code to begin with:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 0)
{
if(indexPath.row == 0)
{
isItemRequired = YES;
if(isItemRequired && count==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Item Required" message:#"You must have to select one or more item in section 2" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
}
}
else
{
isItemRequired = NO;
}
}
else if(indexPath.section == 1)
{
count = 0;
for (int i=0; i < [tableView numberOfRowsInSection:1]; i++)
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:1]];
if(cell.selected==YES)
{
count++;
}
}
}
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 1)
{
count = 0;
for (int i=0; i < [tableView numberOfRowsInSection:1]; i++)
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:1]];
if(cell.selected==YES)
{
count++;
}
}
if(isItemRequired && count==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Item Required" message:#"Atleast one item should be selected in section 2" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
}
}
}

In the didselect method of UITableView, you needs to check the section number & then check which row is clicked from that section
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0)
{
if (indexPath.row == 0)
{
//do this
}
else if (indexPath.row == 1)
{
//do this
}
}
else
{
//do this
}
}

In the following delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
add a check with the help of indexPath returned by the delegate, it will tell you that which section's which row is selected like :
if(indexPath.section == 0 && indexPath.row == 0)
{
// Select something from the another section also
}
else if(indexPath.section == 0 && indexPath.row == 1)
{
// No need to select from another section.
}

First Take one BOOL variable with isYes in .h file like bellow...
BOOL isYes;
after in viewDidLoad: method just assign it to NO like bellow..
isYes = NO;
after that in didSelectRowAtIndexPath delegate method just use like bellow...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.section == 0 && indexPath.row == 0)
{
isYes = YES;
}
else if(indexPath.section == 0 && indexPath.row == 1)
{
isYes = NO;
}
if(isYes){
if(indexPath.section == 1 )
{
//here user can select the section 2
}
}
}
i hope this help you....

Related

UISearchBar with scope buttons NSInternalInconsistencyException Crash on Cancel

I'm at sort of a loss here.
I have a UISearchBar with two scope buttons Option A and Option B. Searching works just fine on both scope buttons but when I click Cancel out of the search bar with the second scope button selected the app will sometimes crash with this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0'
Here's the relevant code for my UITableView:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSArray *results = [fetchedResultsController fetchedObjects];
return [[fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (tableView == self.tableView && [[fetchedResultsController sections] count] > section) {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}
return nil;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *alphabet = [NSArray arrayWithObjects:UITableViewIndexSearch, #"A", #"B", #"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",#"#",nil];
if (tableView == self.tableView) {
return alphabet;
}
return nil;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
if(tableView == self.tableView && [title isEqual:UITableViewIndexSearch]){
[tableView scrollRectToVisible:[[tableView tableHeaderView] bounds] animated:NO];
return -1;
} else if (tableView == self.tableView) {
return [self.fetchedResultsController.sectionIndexTitles indexOfObject:title];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"OptionACell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSManagedObject *category = [fetchedResultsController objectAtIndexPath:indexPath];
if (self.searchBar.selectedScopeButtonIndex == CategoriesViewSearchScopeOptionB && ![self.searchBar.text isEqual:#""]) {
[cell.textLabel setText:[category valueForKey:#"text"]];
} else {
[cell.textLabel setText:[category valueForKey:#"name"]];
}
return cell;
}
And the UISearchBar:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if([self.searchBar.text isEqual: #""] && self.searchBar.selectedScopeButtonIndex == CategoriesViewSearchScopeOptionB) {
self.searchBar.text=#"";
[self updateOptionAFetchRequest];
} else {
[self updateFetchRequest];
NSFetchedResultsController *fetchController = [self fetchedResultsController];
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
[self logSearchTerm:self.searchBar.text];
self.searchBar.text = #"";
self.searchBar.selectedScopeButtonIndex = CategoriesViewSearchScopeOptionA;
[self updateOptionAFetchRequest];
self.searchDisplayController.delegate = nil;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
[self logSearchTerm:self.searchBar.text];
if([self.searchBar.text isEqual: #""]) self.searchBar.selectedScopeButtonIndex = CategoriesViewSearchScopeOptionA;
return YES;
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
if([self.searchBar.text length] > 0) {
[self updateFetchRequest];
}
}
- (void)updateFetchRequest {
if (self.searchBar.selectedScopeButtonIndex == CategoriesViewSearchScopeOptionB) {
[self updateOptionBFetchRequest];
return;
}
[self updateOptionAFetchRequest];
}
I'm having trouble discerning the exact pattern of the crashing. It seems to crash consistently whenever I perform the action of opening the UISearchBar, clicking OptionB then Canceling. But when I open the SearchBar, click back and forth between the scope buttons and perform a couple searches, I'm able to close no problem.
Any help from Core Data experts would be greatly appreciated.

assigning datasource to two tableviews in one view controller

Whats wrong in the following code?
here i am using two table views and assigning them with different data source, but its not working
-(void)viewDidLoad
{
[super viewDidLoad];
arryData = [[NSArray alloc] initWithObjects:#"MCA",#"MBA",#"BTech",#"MTech",nil];
arryData2 = [[NSArray alloc] initWithObjects:#"Objective C",#"C++",#"C#",#".net",nil];
flag=1;
myTable1.hidden=YES;
myTable2.hidden=YES;
btnOne.layer.cornerRadius=8;
btnTwo.layer.cornerRadius=8;
myTable1.layer.cornerRadius=8;
myTable2.layer.cornerRadius=8;
myTable1.delegate=self;
myTable1.dataSource=self;
myTable2.delegate=self;
myTable2.dataSource=self;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.myTable1=tableView)
{
return [arryData count];
}
else {
return [arryData2 count];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView==self.myTable1)
{
static NSString *CellIdentifier1 = #"Cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] ;
}
cell.textLabel.text = [arryData objectAtIndex:indexPath.row];
NSLog(#"1here is%i %#",indexPath.row,cell.textLabel.text);
return cell;
}
else
{
static NSString *CellIdentifier2 = #"Cell2";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] ;
}
cell.textLabel.text = [arryData2 objectAtIndex:indexPath.row];
return cell;
}
}
-(IBAction)btnCategory:(id)sender
{
if (flag==1) {
flag=0;
myTable1.hidden=NO;
myTable2.hidden=YES;
}
else{
flag=1;
myTable1.hidden=YES;
myTable2.hidden=YES;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
myTable1.hidden=YES;
myTable2.hidden=YES;
}
-(IBAction)btnTopic:(id)sender
{
if (flag==1) {
flag=0;
myTable2.hidden=NO;
myTable1.hidden=YES;
}
else{
flag=1;
myTable2.hidden=YES;
myTable1.hidden=YES;
}
}
</code>
when i remove datasource of mytable2 all data gets added to table1 else nothing gets loaded in none of the table.
You did mistake. See my code..
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.myTable1==tableView) // ----- Change here you need to write == symbol instead of = symbol
{
return [arryData count];
} else {
return [arryData2 count];
}
}
Try this,
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView==myTable1)
{
return [arryData count];
}
else {
return [arryData2 count];
}
}
-(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(myTable1==tableView)
{
cell.textLabel.text = [arryData objectAtIndex:indexPath.row];
NSLog(#"1here is%i %#",indexPath.row,cell.textLabel.text);
}
else
{
cell.textLabel.text = [arryData2 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.

How to save selected rows from UITableview to NSString variable?

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.

how to implement code for saving multiple array items through the alertview?

I have implemented code for alert view with textfield here when i click on ok button the textfield entered value is storing in string formate as (str) and i am adding that value to the array in order to i am loading array to the table view but here problem is every time table view consists one item but i want store multiple items entering items from alert and save it as array item for this how to implement code for saving multiple array items through the alertview any one help me to solve this problem in iphone.
myAlert = [[UIAlertView alloc] initWithTitle:#"Enter year"
message:#"alert message"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
[myAlert addTextFieldWithValue:#"" label:#"entervalue"];
alertTextField=[myAlert textFieldAtIndex:0];
alertTextField.keyboardType=UIKeyboardTypeAlphabet;
alertTextField.clearsOnBeginEditing=YES;
alertTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
alertTextField.keyboardAppearance=UIKeyboardAppearanceAlert;
[myAlert show];
[myAlert release];
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:#"Ok"]) {
str = alertTextField.text;
[savedarray addObject:str];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:#"Ok"]) {
str = alertTextField.text;
[savedarray addObject:str];
[self.yourtableview reloadData]; // reload your tableview when add new data in array.
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return savedarray.count;
}
- (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.textLabel.text = [savedarray objectAtIndex:indexPath.row];
return cell;
}
Hope, this will help you..
If i am rit u r asking for something like this:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:#"Ok"])
{
str = alertTextField.text;
if([savedarray Count] < yourRequiredItemsCount)
{
[savedarray addObject:str];
alertTextField = #"";
[alertView show];
}
else
{
[alertView release]; //Release the Alert here.
}
}
}
tell me if it helps! will give u an alternate sol.
If you're allocating the savedarray correctly, then the posted code looks reasonable. The next thing to check is whether you are properly using savedarray as the datasource for the table.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return savedarray.count;
}
- (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.textLabel.text = [savedarray objectAtIndex:indexPath.row];
return cell;
}
Be sure to set the same view controller as the tableview's delegate and datasource.