0

Yes I know people have asked about this for quiet some time.

I'm looking for some help on how to pass data from one view controller to another using @properties..

Instead of posting the code here, I've posted a free sample code which you can get from an open dropbox folder.

Any help is appreciated, but please bear in mind that I'm looking for help, but I'm not developing using storyboard, so I can't use prepareForSeque.

URL: https://www.dropbox.com/sh/l7xagtqqprcjqr2/gplHMvM2-O

Gabriel.Massana
  • 8,165
  • 6
  • 62
  • 81
  • When you initialize viewController, view of this viewController isn't initialized, means view isn't loaded in memory. Unless you write some code like self.view.backgroundColor = [UIColor redColor] that will call viewDidload. – wyp Mar 24 '14 at 14:47

1 Answers1

1

Ok, so, within SecondViewController, you've created a UserText UITextField - what's actually happening is:

  1. SecondViewController *SecondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
  2. SecondView.UserText = TextField.text;
  3. SecondViewController viewDidLoad called, UserText overwritten with correct reference via IBOutlet.

This is pretty much the mistake folks keep making; initialising the viewcontroller, is not a guarantee that the viewDidLoad is called when you want it to be.

So there's a few ways of doing this,

  1. Set an NSString property within SecondViewController
  2. Pass the text into SecondViewController's initWithNibName method like so:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil text:(NSString *) text

Option 2 requires an NSString property. You can't assign text to a UILabel hooked up through an IBOutlet, this is because, viewDidLoad is not called as soon as you initialise the view controller.

user352891
  • 1,181
  • 1
  • 8
  • 14
  • "is not a guarantee that the viewDidLoad is called when you want it to be."... you're right, but it is called when the app launches and by calling SecondView.userText = Textfield.text that would stick throughout the course of the app, which means you don't have to call SecondView.UserText = TextField.text; every time you call an action, or a view appears... – Daniel Ran Lehmann Apr 19 '13 at 18:18
  • But you can't call it before viewDidLoad is called the first time, and the only time to know when viewDidLoad is called, is from inside it, or the viewWillAppear/viewDidAppear methods. Either you store the string as a property, or store the text is a data store outside of the scope of the parentViewController, somewhere where the SecondViewController can access it. Also, the way it's currently set up, it looks like it would leak should you do UserText = TextField (you can't assign TextField.text to UserText because one is an NSString, whilst the other is a UITextField. – user352891 Apr 19 '13 at 19:59