2

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];
Community
  • 1
  • 1
NewToObjectiveC
  • 83
  • 1
  • 2
  • 8
  • MainViewController *mainViewController = [[MainViewController alloc] init]; – Saad Chaudhry Nov 28 '13 at 13:26
  • How do you go from PreviewViewController to MainViewController ? – Marcio Nov 28 '13 at 13:29
  • Please show as the code you use for 'switch the layouts'. The problem might be very trivial: you're passing value to one view controller instance and for displaying - you use another instance of view controller (for example, the one that segue creates for you). – Ossir Nov 28 '13 at 13:31
  • mainViewController.userId = [[NSString alloc] initWithString:@"539897197"]; – Saad Chaudhry Nov 28 '13 at 13:32
  • I edited it and added the part where I switch Layouts – NewToObjectiveC Nov 28 '13 at 13:40
  • [self presentViewController:mainViewController animated:YES completion:NULL]; – Anurag Kabra Nov 28 '13 at 13:44
  • Gee, it's been almost a week since I last saw this question. – Hot Licks Nov 28 '13 at 15:47
  • possible duplicate of [Passing Data between View Controllers](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – Hot Licks Nov 28 '13 at 15:48
  • Are you serious? I'm linking the EXACT SAME POST in my post. Your comment is totally useless. – NewToObjectiveC Nov 29 '13 at 14:27
  • Are you navigating from PreviewViewController to MainViewController using NavigationController or from MainViewController to PreviewViewController ? – Raxit Nov 02 '15 at 11:31
  • If you are navigation from MainViewController to PreviewViewController and you are trying to pass value from PreviewViewController to MainViewController, you will receive null. So let me know the navigation scenario first – Raxit Nov 02 '15 at 11:33

5 Answers5

1

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];
cpjolicoeur
  • 12,766
  • 7
  • 48
  • 59
  • The problem is, that I'm totally new to objective-c. `id` would be the return type, right? But I don't want to return something. I want to set something. I bet I'm totally misunderstanding your answer, but as I said, I'm new to objective-c, I come from android and things there are a lot easier. :p – NewToObjectiveC Nov 28 '13 at 13:35
  • I updated my response to be a bit more thorough. Basically you will just make a custom init method in your view controller and call that instead of the superclasses initWithNibName – cpjolicoeur Nov 28 '13 at 15:12
0

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";;
    }
}
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
0
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

Anurag Kabra
  • 444
  • 1
  • 5
  • 18
0

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

Community
  • 1
  • 1
user3182143
  • 9,459
  • 3
  • 32
  • 39
-1

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];
  • Please try and add more detail to your answer because answers that just say try this aren't very good answers at all. – Popeye Nov 02 '15 at 11:35
  • Please tell me the reason for down voting my answer. – Manikandan tamilselvan Nov 02 '15 at 11:50
  • My answer is correct and try my answer.If my answer does not work, I will accept the down voting.This works perfectly correct. – Manikandan tamilselvan Nov 02 '15 at 11:51
  • The downvote was for the lack of information regarding your answer. Just putting try this isn't a very good answer, please read http://stackoverflow.com/help/how-to-answer know how to write a good answer. Also my downvote was perfectly valid, because of the lack of information. – Popeye Nov 02 '15 at 11:58
  • now i can change my answer for different way. Then you don`t change the downvote – Manikandan tamilselvan Nov 02 '15 at 12:05
  • I'm very reluctant to change my vote. The reason being is that your answer adds no value above what the other answers already have provided. If you are going to add an answer this late in the game you need to be providing a lot more information then you already have, you need to add value and that is very hard to do when there are already answers and the question is so old. – Popeye Nov 02 '15 at 12:08
  • A good example of what I mean can be found in the answer by `user3182143` (http://stackoverflow.com/questions/20267387/pass-a-value-from-one-viewcontroller-to-another-in-objective-c/33477279#33477279) they have provide a lot of information that adds a lot of value to what has already been provided. – Popeye Nov 02 '15 at 12:12