1

I know that this question is really old, but I'm having a lot of trouble accessing NSString's from another class;

Let's say that I have FirstViewController and SecondViewController, and from the Second I want to access a NSString called string - which is in FirstViewController -(okay, I know it's obvious). Here's the code of the SecondViewController:

FirstViewController *viewController = [[FirstViewController alloc] init];
NSLog(@"%@", viewController.string);

But the result is (null), because it's getting the value from the init method.

Anyone have some tip/solution to access the string from any place that it's declared?

Thanks!

  • Actually, @dasblinkenlight, I still get `(null)` as the string log. –  Aug 05 '12 at 23:14
  • @Alberto From your question it looks like reading http://stackoverflow.com/questions/10159295/calling-nsview-from-other-class-thats-already-initialized/10159478#10159478 may help a bit (I may be wrong) – Vervious Aug 05 '12 at 23:39

2 Answers2

1

If you're doing what I think you are doing, you're creating a new version of FirstViewController within second view controller which, unless the FirstViewController.string is initialized to some value in the init block, is going to return a nul value.

What I think you want is to get the value of the string by accessing the item from the already-created FirstViewController. There are various ways to do this (depending on how you are pushing SecondViewController from the first and whether or not you are using Storyboards or not.

  • The `SecondViewController` is a subview from `FirstViewController`. Any idea? –  Aug 05 '12 at 23:16
  • 1
    Try casting `self.parentViewController` to `SecondViewController` and accessing its properties that way. `SecondViewController *parent = (SecondViewController*)self.parentViewController; NSString* firstVCString = parent.stringProperty`; – Christopher Jones Aug 05 '12 at 23:20
0

Global Variable is probably your answer. Unless you are in a tab bar controller, it is not possible to "PULL" the data from another class. It is possible to push your values from ViewController1 onto your ViewController2, but in order to pull it, I'd say global variable will save you lots of headache.

If Pollavith
  • 228
  • 2
  • 5