Plz code Help Can anyone tell me how to do that task? In main screen user selects footballer,in 2nd screen in Table view cell user select specific row and save that row and go back to main view.in main view then it shows the specific row videos. Basically i want to know about speific row selection,save that selection in table view and show thier contetnts in main screen.
-
3Study a little bit about delegation. – Bourne Nov 13 '13 at 06:20
-
@Bourne I would have given you more UP's if only possible. :P – Dunes Buggy Nov 13 '13 at 06:21
-
For get selected row's data in first view controller you need to create protocol..http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c and http://stackoverflow.com/questions/5244830/using-a-delegate-to-pass-data-back-up-the-navigation-stack – iPatel Nov 13 '13 at 06:21
-
You can use this github repo [JLSelectionTVC](https://github.com/nvrtdfrst/JLSelectionTVC) which accomplishes that – nvrtd frst Apr 15 '14 at 19:14
4 Answers
go through the below code, it implements the delegate concept and also implements the solution for ur question hope this helps u :)
//in your main view controller
#import "ViewController.h"
#import "FootBallPlayersViewController.h"
@interface ViewController ()<FootballPlayerDelegate>//confirms to this delegate
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)whenSelectButtonClicked:(id)sender
{
FootBallPlayersViewController *controller = [[FootBallPlayersViewController alloc]initWithNibName:@"FootBallPlayersViewController" bundle:nil];
controller.delegate = self; //u must set to self
[self presentViewController:controller animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)selectedFootBallPlayer:(NSString *)player
{
//implementation of your delegate method
//hear u are getting the football player name and u can continue further hear
NSLog(@"%@",player);
if([player isEqualToString:@"player1"])
{
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTitle:player forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(whenFirstPlayerButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; //add the target to self for click events
aButton.frame = CGRectMake(50, 50, 200, 55);
[self.view addSubview:aButton];
}
else
{
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTitle:player forState:UIControlStateNormal];
aButton.frame = CGRectMake(50, 105, 200, 55);
[aButton addTarget:self action:@selector(whenSecondPlayerButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; //same hear
[self.view addSubview:aButton];
}
}
//now define the action methods
- (void)whenFirstPlayerButtonClicked:(UIButton *)sender
{
NSLog(@"player 1 video start");
}
- (void)whenSecondPlayerButtonClicked:(UIButton *)sender
{
NSLog(@"player 2 video start ");
}
@end
in the view that contain's the tableview do somthing like this
//in FootBallPlayersViewController.h
#import <UIKit/UIKit.h>
@protocol FootballPlayerDelegate <NSObject> //define a protocol named FootballPlayerDelegate
- (void)selectedFootBallPlayer:(NSString *)player;
@end
@interface FootBallPlayersViewController : UIViewController
{
NSArray *players;
NSString *selectedPlayer;
}
@property (retain, nonatomic) IBOutlet UITableView *playerTable;
@property (nonatomic, assign) id<FootballPlayerDelegate>delegate; //create a delegate
@end
in your FootBallPlayersViewController.m
file
#import "FootBallPlayersViewController.h"
@interface FootBallPlayersViewController ()<UITableViewDataSource,UITableViewDelegate>
{
}
@end
@implementation FootBallPlayersViewController
@synthesize delegate; //synthesizing the delegate
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
players = [[NSArray alloc]initWithObjects:@"player1",@"player2", nil];
// players = [[NSArray alloc]initWithObjects:@"player1","player2", nil];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc
{
[players release];
[_playerTable release];
[super dealloc];
}
- (IBAction)whenDoneButtonClicked:(id)sender {
//when done button clicked -->
//send a delegate to main controller
if([self.delegate respondsToSelector:@selector(selectedFootBallPlayer:)])//to avoid crash
{
[self.delegate selectedFootBallPlayer:selectedPlayer]; //call the delegate method hear
}
//dismiss the view
[self dismissViewControllerAnimated:YES completion:nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return players.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = [players objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//u can manage check mark and all, i am getting the selected player name
selectedPlayer = [players objectAtIndex:indexPath.row];
}
@end

- 8,394
- 6
- 41
- 53
-
-
if u got any thing wrong pls comment so that i can move closer to your answer don't down vote blindly – Shankar BS Nov 13 '13 at 09:25
-
Awesome Shan! You have done great work for me Thank You sir! :) My problem Solved. – user2396021 Nov 13 '13 at 11:59
-
-
Dear Shan! Can you tell me how to add actions to buttons to play videos in main view controller? Here is your code NSLog(@"%@",player); if([player isEqualToString:@"player1"]) { UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [aButton setTitle:player forState:UIControlStateNormal]; aButton.frame = CGRectMake(50, 50, 200, 55); [self.view addSubview:aButton]; – user2396021 Nov 19 '13 at 04:33
-
-
-
Thanks Shan ! But what if i first add buttons to the interface builder? Plz shan i'm really stuck here. – user2396021 Nov 19 '13 at 05:37
-
-
-
-
Shan i'm new to this blog i don't realy know the voting system here! – user2396021 Nov 19 '13 at 06:30
-
-
You mean when i clicked up that it maens +ve voting and if i clicked down it means -ve voting? Am I Right? – user2396021 Nov 19 '13 at 06:33
-
ya and also if u click on check mark it will appears green it means u are accepted the answer it appears left to vote .. try it – Shankar BS Nov 19 '13 at 06:34
-
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/41455/discussion-between-shan-and-user2396021) – Shankar BS Nov 19 '13 at 06:43
-
Simple solution ... As you are a newbie , I am clarifying each point.
First make a property in AppDelegate.h
@property int selectedRow;
Save the selected indexpath.row in 2nd screen that is your Table view screen, and also import AppDelegate.h
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate]; self.appDelegate.selectedRow=indexPath.row; //saving the row }
On main screen's viewWillAppear()
-(void)viewWillAppear:(BOOL)animated { if(self.appDelegate.selectedRow!=-1)//check wether row is selected or not { //action to show the specific row videos } }

- 9,135
- 1
- 41
- 79
-
Sir there is Error coming in self.appDelegate. I imported appDelegate.h but still error what i do? – user2396021 Nov 13 '13 at 07:59
-
in 2nd screen that is your Table view screen, in its .h file make a property @property (strong, nonatomic) AppDelegate * appDelegate; – Vizllx Nov 13 '13 at 08:21
-
-
1@user2396021-> give screenshot... or upload the code here, and what is the error? – Vizllx Nov 13 '13 at 09:04
-
the app delegate should not be misused for routing data through the app. it's purpose is to deal with system events. instead use delegation and/or notifications. – vikingosegundo Nov 19 '13 at 08:35
Good Ways to accomplish this:
- Custom Delegate
NSNotificationCenter
NSUserDefaults
(edit: unnecessary disk writes)- Maintaining a Common NSObject Subclass and refreshing data on
-willAppear
Other Ways:
- Database (Core Data / SQLite) or plist (all too heavy for your case) (edit: unnecessary disk writes)
UIPasteBoard
A quick delegate tutorial:
Part 1: Creating the delegate
Suppose this is in the .h of the UITableViewController
subclass that I have named YourTableViewControllerClassName
//declare the protocol
@class YourTableViewControllerClassName;
@protocol YourTableViewControllerClassNameDelegate <NSObject>
//@required //uncomment to specify required delegate methods as below
//- (void)requiredMethodNotUsedForThisExample;
@optional
- (void)selectedRow: (NSString *)selectedObj;
@end
@interface YourTableViewControllerClassName : UITableViewController
//declare a weak property to store any object
@property (nonatomic, weak) id <YourTableViewControllerClassNameDelegate> delegate;
@end
Suppose this is the -didSelectRowAtIndexPath
of the corresponding UITableViewController
subclass:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//the following line is the main thing and can be called
//in any method within this class (placed wisely)
if([[self delegate] respondsToSelector:@selector(selectedRow)]) { //avoid crash
[[self delegate] selectedRow:cell.textLabel.text];
}
[self.navigationController popViewControllerAnimated:YES];
}
Part 2: Implementing the delegate
Suppose this is the code somewhere in the former UIViewController
subclass:
//call this method somewhere
-(void)pushMyTableViewController
{
//declare "UILabel lblText;" in the .h of this class
//lblText = [UILabel alloc] init];
//[lblText setFrame: CGRectMake(0,0,100,35)];
//[self.view addSubview:lblText];
YourTableViewControllerClassName *tvcObj = [[YourTableViewControllerClassName alloc] init];
//for the following line, remember to declare
//<YourTableViewControllerClassNameDelegate> in the .h of this class
//hence declaring that this class conforms to the delegate protocol
[tvcObj setDelegate:self];
[self.navigationController pushViewController:tvcObj animated:YES];
}
And this will be the delegate method you could implement in the former UIViewController
subclass:
#pragma mark - Optional YourTableViewControllerClassName Delegate Methods
-(void)selectedRow:(NSString *)selectedObj
{
[lblText setText:selectedObj];
}
NOTE: This will not solve your particular issue because we are only setting a label depending on the selected row from the UITableViewController
subclass.
The point was to show how delegation works.
Also, if you can get the cell.textLabel.text
and set it on a UILabel
in the former class then you can make changes at the appropriate places (mainly the method/s within @protocol
)and pass the array index of the selected item instead or any object/variable/whatever that makes your life easier
*If you want something easier then go for NSNotificationCenter
or NSUserDefaults
or maybe even UIPasteBoard
(if it floats your boat)

- 19,275
- 6
- 69
- 98
-
i wonder which ghost downvoted me on this. If there are any mistakes, please comment. Also, any improvements or insights will be appreciated (_We're all here to learn and teach, so refrain from demotivating people from answering_). Anyways... i'll keep this around for myself... just incase i ever forget how to make a custom delegate :P – staticVoidMan Nov 16 '13 at 18:16
-
-
@vikingosegundo: ok but honestly i don't know enough to know what is bad. some guidance would be greatly appreciated – staticVoidMan Nov 19 '13 at 04:56
-
honestly: it is your answer. if you don't know, what is bad you should investigate it yourself. start with NSUserDefaults. – vikingosegundo Nov 19 '13 at 04:58
-
@vikingosegundo: there are only 6 ways i have mentioned. i am sure you won't like `NSUserDefaults` or `UIPasteBoard` but they do the trick unless you want to make a killer robot. – staticVoidMan Nov 19 '13 at 05:00
-
so just to pass data form one controller to the other you would possibly save data persistently, hit the disk or a database? Curing cancer by shooting the patient also does the trick. – vikingosegundo Nov 19 '13 at 05:17
-
1 is perfect, 2 is good, 3 is bad, 4 makes no sense, 5 and 6 are some of the dumbest advices I have ever heard of. – vikingosegundo Nov 19 '13 at 05:20
-
@vikingosegundo: haha. i guess i was sliding down with bad ideas. _thanks for your honest opinion_. – staticVoidMan Nov 19 '13 at 05:21
-
You should try to give good or perfect answers — not all answers. – vikingosegundo Nov 19 '13 at 05:22
Use the tableView delegate called when you select any row
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
appDelegate.selectedindex = indexpath.row;
or
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:indexpath.row] forKey:@"SelcetedIndex"];
}
then there is 3 things you can do to get your selected index
1) make a app delegate variable for index path so that you can set here and get the value on other controller
// add property at appDelegate file @property int selectedIndex;
2) Using NSUserDefault to set the selected index value
// read userDefault value
[[[NSUserDefaults standardUserDefaults] objectForKey:@"SelcetedIndex"] intValue];
3) using delegate to return back the value to previous controller
// try to google and first understand the concept and let me know if you want to go with delgate

- 3,985
- 2
- 17
- 41
-
-
I googled and clear the delegate concept. So what will be the code in this case? :) – user2396021 Nov 13 '13 at 08:40