1

I know this question has been asked a billion times, but my particular question hasn't been answered. So sorry about the repetitiveness.

So I know how to declare and define extern variables (correct me if I'm wrong):

in foo.h file:

extern NSString *foo;

in foo.m file:

NSString *foo = @"fooey";

But then say I want to access/change the variable in the hoo.m file. How would I do that?

DonyorM
  • 1,760
  • 1
  • 20
  • 34

1 Answers1

1

In .h

 @interface SOViewController : UIViewController{
    NSString * variable;
 }

in .m you can set it wherever.

For example, viewDidLoad.

You can also declare this in the .m file by putting the declaration

@interface SOViewController(){
    NSString * variable;
}
  // @property (strong, nonatomic) NSString * myString; might be appropriate here instead
@end

Before the @implementation.

Ideally, since this is object-oriented programming, though, best practice would be to make the string a property of the class.

If you are really set on the extern keyword here is a stackoverflow post on how to use it Objective C - How to use extern variables?

EDIT

The question came down to how to pass variables around. You can look at this article How to pass prepareForSegue: an object to see an example of how to do that with seguing.

Community
  • 1
  • 1
AdamG
  • 3,718
  • 2
  • 18
  • 28
  • Yes, that's how you define/declare it. But how do I access it in a different class besides foo.h/m? – DonyorM Aug 31 '13 at 03:40
  • Ah, I see. You would need to pass it to that class. – AdamG Aug 31 '13 at 03:41
  • Declare it as an external variable (.h) and then in prepareForSegue or when you declare the new viewController set a property in that viewController where you need it. – AdamG Aug 31 '13 at 03:42
  • Ok, so set it as a property in a different viewController. Do you have a link for how to do that? Or you could put it in the answer. – DonyorM Aug 31 '13 at 03:44
  • http://stackoverflow.com/questions/7864371/ios5-how-to-pass-prepareforsegue-an-object is an example of how to do this with segues. – AdamG Aug 31 '13 at 03:46