DonyorM
DonyorM

Reputation: 1800

Use and Access Global/Extern Variables in Objective C

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?

Upvotes: 1

Views: 3040

Answers (1)

AdamG
AdamG

Reputation: 3718

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.

Upvotes: 1

Related Questions