passing data from view controller to another - ios

i have to view controllers .. and i want to pass data from the first to the second view i have this code
for the ViewController.h
#import <UIKit/UIKit.h>
#import "SecondView.h"
#interface ViewController : UIViewController{
SecondView *secondviewData;
IBOutlet UITextField *textfield;
}
#property (nonatomic,retain) SecondView *secondviewData;
-(IBAction)passdata:(id)sender;
#end
for the viewController.m
#import "ViewController.h"
#import "SecondView.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize secondviewData;
-(IBAction)passdata:(id)sender{
SecondView *second= [[SecondView alloc] initWithNibName:nil bundle:nil];
self.secondviewData=second;
secondviewData.passedValue=textfield.text;
[self presentModalViewController:second animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
for the second view controller which is SecondView.h
#import <UIKit/UIKit.h>
#interface SecondView : UIViewController{
IBOutlet UILabel *label;
NSString *passedValue;
}
#property (nonatomic,retain) NSString *passedValue;
-(IBAction)back:(id)sender;
#end
for the SecondView.m
#import "SecondView.h"
#import "ViewController.h"
#interface SecondView ()
#end
#implementation SecondView
#synthesize passedValue;
-(IBAction)back:(id)sender{
ViewController *vc= [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:vc animated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
label.text=passedValue;
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
the error I'm having is presentModalViewController deprecated iOS 6 in these 2 lines
[self presentModalViewController:vc animated:YES];
[self presentModalViewController:vc animated:YES];
and when i run it and click on the button it will stop working and displays a blank black page

You can save data in AppDelegate to access it across view controllers in your application. All you have to do is create a shared instance of AppDelegate
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

If you are building for >= iOS 5 then you should be using presentViewController:animated:completion: instead of presentModalViewController:animated:.
Also, the idea of 'back' doesn't usually mean pushing something new. So, this code:
- (IBAction)back:(id)sender {
ViewController *vc= [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:vc animated:YES];
}
should change to:
- (IBAction)back:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
Now, you should look at using a delegate pattern to pass the data back to the originating view controller. And preferably that delegate implementation would include telling the delegate that the second controller is finished and the delegate triggers the dismiss.
See Passing Data between View Controllers

Related

Passing data to method in Tab Bar View Controller Before ViewDidLoad

I have two view controllers used in a Tab Bar Controller: FirstViewController and SecondViewController. I'm trying to call a method in the SecondViewController from the FirstViewController, but do this before the SecondViewController is loaded by selecting the Second Tab. Is this possible? I've tried notifications and delegates and can't seem to get it to work, unless I select the SecondViewController and run ViewDidLoad first, and then call it from the FirstViewController.
This is in objective-c and I'm trying to call setAutoModeTimer() in the SecondViewController.
Here is my code:
FirstViewController.h
#import <UIKit/UIKit.h>
#protocol FirstViewControllerDelegate <NSObject>
- (void) setAutoModeTimer;
#end
#interface FirstViewController : UIViewController
#property (nonatomic,weak) id <FirstViewControllerDelegate> delegate;
#end
FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
SecondViewController * myViewController = [[SecondViewController alloc] init];
[myViewController view];
// Do any additional setup after loading the view, typically from a nib.
}
//- (void)loadView{[self.tabBarController.viewControllers makeObjectsPerformSelector:#selector(view)];}
- (IBAction)startTimerButtonPressed:(id)sender {
[self.delegate setAutoModeTimer];
}
#end
SecondViewController.h
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
#end
SecondViewController.m
#import "SecondViewController.h"
#import "FirstViewController.h"
#interface SecondViewController () <FirstViewControllerDelegate>
#end
#implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
FirstViewController *firstVC = [self.storyboard instantiateViewControllerWithIdentifier:#"FirstViewController"];
firstVC.delegate = self;
}
- (void) setAutoModeTimer
{
NSLog(#"Timer has started");
}
#end
You don't need to keep references in each view controller for another one. What are you doing is creating new instances of UIViewControllers in each view controller.
FirstViewController *firstVC = [self.storyboard instantiateViewControllerWithIdentifier:#"FirstViewController"];
firstVC.delegate = self;
After viewDidLoad will be finished firstVC instance will be released.
Because you created a local var. It is not the same viewController you have in tabBar.
You need to setup connection between view controllers once.
It can be done by setup your UITabBarController programmatically, not in stroryboard.
You can setup viewControllers of UITabBarController once, and setup connections between them.
#import "SecondViewController.h"
#import "FirstViewController.h"
#implementation MainTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *listOfViewControllers = [[NSMutableArray alloc] init];
FirstViewController *firstVC = [self.storyboard instantiateViewControllerWithIdentifier:#"FirstViewController"];
SecondViewController * secondVC = [[SecondViewController alloc] init];
firstVC.delegate = secondVC;
[listOfViewControllers addObject:firstVC];
[listOfViewControllers addObject:secondVC];
[self setViewControllers:listOfViewControllers
animated:YES];
}

Protocol/Delegate is not working

I have three UIViewcontroller, namely ViewController, BViewController and CViewController, ViewController is RootViewController from UINavigationController,
I'm pushing from ViewController -> BViewController -> CViewController, through button action.
I have declared protocol in CViewController. This protocol method is working fine for BViewController, but I don't understand how to make work its delegate method in ViewController.
I had created an object of CViewController in View Controller, then declared self for that delegate, though its not working, Below is my code. Please help me. Where I'm doing wrong here !
My Root View Controller, namely ViewController
#import "ViewController.h"
#import "BViewController.h"
#import "CViewController.h"
#interface ViewController ()<testDelegates>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CViewController *cVC = [self.storyboard instantiateViewControllerWithIdentifier:#"CViewController"];
cVC.mydelegate = self;
}
- (IBAction)nextAction:(id)sender {
BViewController *bViewC = [self.storyboard instantiateViewControllerWithIdentifier:#"BViewController"];
[self.navigationController pushViewController:bViewC animated:YES];
}
-(void)TestMethod{
NSLog(#" Its NOT Working");
}
My Second View Controller, Namely BViewController
#import "BViewController.h"
#import "CViewController.h"
#interface BViewController ()<testDelegates>
#end
#implementation BViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)bNextAction:(id)sender {
CViewController *cVC = [self.storyboard instantiateViewControllerWithIdentifier:#"CViewController"];
// cVC.mydelegate = self;
[self.navigationController pushViewController:cVC animated:YES];
}
-(void)TestMethod{
NSLog(#" Its Working If I uncomment to cVC.mydelegate = self");
}
And my third View Controller, Where i Declared a protocol in .h file, namely CViewController
#import <UIKit/UIKit.h>
#protocol testDelegates <NSObject>
-(void)TestMethod;
#end
#interface CViewController : UIViewController
#property (weak) id <testDelegates> mydelegate;
#end
And in .m file
#import "CViewController.h"
#interface CViewController ()
#end
#implementation CViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)cNextAction:(id)sender {
[self.mydelegate TestMethod];
}
You create class and this class destroying after you leave viewDidLoad method.
- (void)viewDidLoad {
[super viewDidLoad];
CViewController *cVC = [self.storyboard instantiateViewControllerWithIdentifier:#"CViewController"];
cVC.mydelegate = self;
}
As I understand you need to perform some methods in the ViewController from the CViewController.
You can pass viewController as delegate from the BViewController and them past it to the CViewController.
Or you can use code like this:
- (IBAction)cNextAction:(id)sender {
id< testDelegates > delegate = self.navigationController.viewControllers[0];
if([delegate conformsToProtocol:#protocol(testDelegates)])
{
[delegate TestMethod];
}
}
This is no best way but it's will be work.
Try this
self.delegate = self.navigationController.viewControllers[0];
You need to declare a another Protocol into BViewController class.
Please follow below steps.
Step 1: BViewController.h
#protocol testDelegates2 <NSObject>
-(void)TestMethod2;
#interface BViewController : UIViewController
#property (weak) id <testDelegates> mydelegate;
#end
#implementation CViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)cNextAction:(id)sender {
[self.mydelegate TestMethod2];
}
Step 2. In ViewController class conform Protocol
#interface ViewController ()<testDelegates>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CViewController *cVC = [self.storyboard instantiateViewControllerWithIdentifier:#"CViewController"];
cVC.mydelegate = self;
}
- (IBAction)nextAction:(id)sender {
BViewController *bViewC = [self.storyboard instantiateViewControllerWithIdentifier:#"BViewController"];
cVC.mydelegate = self; //important line
[self.navigationController pushViewController:bViewC animated:YES];
}
-(void)TestMethod2{
NSLog(#"Final Output");
}
If Your are trying to set Delegate of CViewController to ViewController then
try putting
self.mydelegate = self.navigationController.viewControllers[0]
on viewDidLoad method of CViewController.
Else you are Trying to make ViewController And BViewController both be Delegate of CViewController then this is not possible like this, as Delegate of a Object Can only be unique. This means the delegate is simply a variable which holds reference of object and as you know value to a variable can be unique at a instance of time.
So If you are willing to do some task on both Viewcontroller and BViewController then use notification pattern. See apple doc here

how to add a navigation controller to a view that is not the main view?

im a beginner and trying to figure out how to work with nib properly.
I have a HomeViewController.h:
#import <UIKit/UIKit.h>
#import "StackTableViewController.h"
#interface HomeViewController : UIViewController
#property (strong, nonatomic) StackTableViewController *stackViewController;
- (IBAction)goToStack:(id)sender;
#end
HomeViewController.m:
#import "HomeViewController.h"
#interface HomeViewController ()
#end
#implementation HomeViewController
- (id)init {
self = [super initWithNibName:#"HomeViewController" bundle:nil];
if (self) {
//
_stackViewController = [[StackTableViewController alloc]init];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)goToStack:(id)sender {
//[self.navigationController showViewController:_stackViewController sender:self];
[self presentViewController:_stackViewController animated:YES completion:nil];
}
As you can see I'm modelling from the HomeViewController to StackTableViewController...
Now it works ok, but I want that StackTableViewController will be embedded in NavigationController...that I can put a cancel button in the top.
This is my StackTableViewController.m:
#import "StackTableViewController.h"
#interface StackTableViewController ()
#property (strong, nonatomic) UINavigationController *navBar;
#end
#implementation StackTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
// Return the number of rows in the section.
return 0;
}
What should I add to the viewDidLoad method that will embed the navBar in the tableview?
tnx
There is not need to declare StackTableViewController as a property of HomeViewController, just modify goToStack like so:
- (IBAction)goToStack:(id)sender {
StackTableViewController *stackViewController = [[StackTableViewController alloc] init]; // shouldnt this get loaded from a NIB though???
[self presentViewController:stackViewController animated:YES completion:nil];
}
About youer issue with UINavigationController, depending on your setup the UINavigationController is the base for a certain navigation stack within your app, so, if you're just building a simple app without a tab bar or another more complex interface, your UINavigationController might be the rootViewController of your application's main UIWindow (a property of your AppDelegate).
So, what you will have to do to get this setup to work is in application:didFinishLaunchinWithOptions of your AppDelegate, set the application's root window:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:#"HomeViewController" bundle:nil]; // I assume you have a NIB file called HomeViewController
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:homeViewController];
self.window.rootViewController = navigationController;
return YES;
}
This will have the effect that the HomeViewController that you will see on application startup, is embedded within an instance of UINavigationController, which again is the rootViewController of your whole application.
Then again, you can modify goToStack to use this instance of UINavigationController instead of showing stackViewController modally:
- (IBAction)goToStack:(id)sender {
StackTableViewController *stackViewController = [[StackTableViewController alloc] init]; // shouldnt this get loaded from a NIB though???
[self.navigationController pushViewController:stackViewController animated:YES];
}
You can use self.navigationController here because homeViewController is embedded in a UINavigaitonController, so iOS will set this property for you.
Hope that helps! :)
Update:
If you don't want to have your HomeViewController embedded within the UINavigationController, just modify goToStack like so:
- (IBAction)goToStack:(id)sender {
StackTableViewController *stackViewController = [[StackTableViewController alloc] init]; // shouldnt this get loaded from a NIB though???
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:stackViewController];
[self presentViewController:navigationController animated:YES completion:nil];
}

Button action not thrown

I am creating an iOS app. On a view controller there are several buttons.
One of them is the AButton, here you have my header file:
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController
- (IBAction)Aaction:(id)sender;
#property (weak, nonatomic) IBOutlet UIButton *AButton;
#end
I want to open another view controller when AButton is tapped:
#import "FirstViewController.h"
#import "EntradasTableViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Aaction:(id)sender {
EntradasTableViewController *detailViewController =[self.storyboard instantiateViewControllerWithIdentifier:#"entradasViewController"];
detailViewController.categoriaDescription = #"A";
[self.navigationController pushViewController:detailViewController animated:YES];
}
#end
I have declared the StoryBoard identifier as follows:
But after tapping on the button nothing happens, no exception is thrown and the view controller detailViewController is not shown.
Any help is welcome.
NEW IMAGED ADDED:
Here is a screenshot where I am declaring the action for the button in the storyboard:
The problem is that your FirstViewController instance is not in a navigation interface. Therefore when your FirstViewController says self.navigationController, that's nil. Therefore this line:
[self.navigationController pushViewController:detailViewController animated:YES];
...involves sending a message to nil. In Objective-C, sending a message to nil does nothing. So that's why nothing happens.

Pass a value from one ViewController to another in Objective-C

I'm fairly new to Objective-C, programming. The one thing, I'm currently putting up with is passing a value from the first ViewController to the next one.
I've read this entry here and it didn't help me. Which is funny, since his answer has nearly 500 votes, so I must be the problem. What I did was the following.
I opened my PreviewViewController.m and added the following line #import "MainViewController.h" since I wanted to pass a value from the PreviewViewController to the `MainViewController. Then, when I switch the layouts ( which successfully works ) I want to pass a value.
MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainViewController.userId = #"539897197";
As you can see, I want to pass the userId. For that, I also created a property in the MainViewController.h
#property ( nonatomic, strong ) NSString *userId;
Now, In my MainViewController.m I want to access the userId. But when I log it, the console tells me it is null. However, when I set the variable right before the NSLog it works, so it seems like the passing is the problem.
Additionally in the MainViewController.m I have the following line
#synthesize userId = _userId;
but even when I removed that line and changed the NSLog to NSLog(#"%#",self.userId); the same problem occurred.
How can I successfully pass the variables? Which step am I doing wrong?
EDIT
This is how I switch the layouts
UIViewController *viewController = [[MainViewController alloc]init];
MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainViewController.userId = #"539897197";
[self presentViewController:viewController animated:YES completion:NULL];
Why not create a custom initializer and pass it in that way? Something like
- (id)initWithUserId:(NSString *)aUserId {
self = [super initWithNibName:#"MainViewController" bundle:nil];
if (self) {
self.userId = aUserId
}
return self;
}
Then you can just do:
MainViewController *mvc = [[MainViewController alloc] initWithUserId:#"1234"]
[self presentViewController:mvc animated:YES completion:nil];
If you are using storyboard then you should use prepareForSegue: method to pass data between view controllers. First Create the segue from your PreviewViewController to MainViewController, just control drag from your view controller to next viewcontroller to create segue. Use UINavigationController if you are using push segue. Use this method to segue and pass data
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"yourSegueIndentifier"]){
MainViewController *mvc = (MainViewController *) segue.destinationViewController;
mvc.userId = #"539897197";;
}
}
UIViewController *viewController = [[MainViewController alloc]init];
MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainViewController.userId = #"539897197";
[self presentViewController:mainViewController animated:YES completion:NULL];
use mainViewController rather than viewController when presenting the view controller
Here we have two ways for passing data.
First is Custom Delegate
Second is NSNotification
Here we have two view controllers.
ViewController
and
SecondViewController
in SecondViewController
.h
#import <UIKit/UIKit.h>
#class SecondViewController;
#protocol SecondViewControllerDelegate <NSObject>
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text;
#end
#interface SecondViewController : UIViewController
#property (nonatomic, assign)id<SecondViewControllerDelegate> delegate;
#property (nonatomic, strong) IBOutlet UITextField *nameTextField;//It must connect as outlet connection
- (IBAction)doneButtonTapped:(id)sender;
#end
.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
//Either use NSNotification or Delegate
- (IBAction)doneButtonTapped:(id)sender;
{
//Use Notification
[[NSNotificationCenter defaultCenter] postNotificationName:#"passingDataFromSecondViewToFirstView" object:self.nameTextField.text];
//OR Custom Delegate
[self.delegate secondViewController:self didEnterText:self.nameTextField.text];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
in ViewController
.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface ViewController : UIViewController<SecondViewControllerDelegate>
#property (nonatomic, strong) IBOutlet UILabel *labelName; //You must connect the label with outlet connection
- (IBAction)gotoNextView:(id)sender;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//addObserver here...
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(textFromPreviousViewControllerNotificationReceived:) name:#"passingDataFromSecondViewToFirstView" object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
//addObserver Method here....
- (void)textFromPreviousViewControllerNotificationReceived:(NSNotification *)notification
{
// set text to label...
NSString *string = [notification object];
self.labelName.text = string;
}
- (IBAction)gotoNextView:(id)sender;
{
//If you use storyboard
SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"SecondViewController"];
//OR If you use XIB
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
secondViewController.delegate = self;
[self.navigationController pushViewController:secondViewController animated:YES];
}
//Calling custom delegate method
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text
{
self.labelName.text = text; //Getting the data and assign the data to label here.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
For your understanding the code I create a simple passing data from one second view controller to first view controller.
First we navigate the view from first view controller to second view controller.
After that we send the data from second view controller to first view controller.
NOTE : You can either use NSNotification or Custom Delegate method for sending data from One View Controller to Other View Controller
If you use NSNotification, you need to set the postNotificationName for getting data in button action method.
Next you need to write addObserver in (sending data to your required View Controller) ViewController and call the addObserver method in same View Controller.
If you use custom delegate,
Usually we go with Custom Protocol Delegate and also we need to Assign the delegate here.
Very importantly we have to set the Custom Delegate Method in the Second View Controller.Because where we send the data to first view controller once we click the done button in second view controller.
Finally we must call the Custom Delegate Method in First View Controller, where we get the data and assign that data to label.Now you can see the passed data using custom delegate.
Likewise you can send the data to other view controller using Custom Delegate Methods
I tried and got the solution for passing the value between viewcontroller.
MainViewController *mainVC = [[self storyboard] instantiateViewControllerWithIdentifier:#"MainViewController"];
mainVC.userId = #"539897197";
[self presentViewController:mainVC animated:YES completion:Nil];
or using this way . You don`t use the storyboard use the following its working fine
MainViewController *mainVC = [[MainViewController alloc] init];
mainVC.userId = #"539897197";
[self presentViewController:mainVC animated:YES completion:Nil];

Resources