IPhoneCrazy
IPhoneCrazy

Reputation: 33

Global variables in IPHONE APP

How to declare and use global variable with extern in Objective C and other files.

I want to define and assign the global variable in 1.h file and 1.m and want to use that in 2.m file

I am defining

1.h

extern const NSString *str;

1.m

NSString *str=@"HELLO";

in 2.m I am importing the 1.h

want to access str but giving me 2.o error.

Upvotes: 0

Views: 2784

Answers (4)

If you have central values you want to store and modify from a number of classes, think about putting them into either a singleton object, or the application delegate (really also a singleton). Then they are "global" but you have a better idea of what is accessing what.

Upvotes: 0

Abizern
Abizern

Reputation: 150575

You say:

m defining 1.h extern const NSString *str; 1.m NSString *str=@"HELLO"

This isn't a way to pass global strings around, its a way of using a constant NSString instead of having to type in the static string each time.

And anyway, writing

extern const NSString *str;

the const is pointless because NSString is immutable. You should really be declaring these as

extern NSString * const str;

In this case, the actual pointer is a constant, which is probably the desired behaviour.

Anyay; I agree with PeyloW, passing values around in a global should be rethought. I'm not saying it shouldn't be done, just that you shouldn't reach for that as the first method of passing state around.

Upvotes: 0

PeyloW
PeyloW

Reputation: 36752

Global variables is a good sign of a bad design. I am guessing, based on your previous comment, that what you want to do is sending a string from one view controller, to another. There are two proper ways to do this:

Let the sending class also define a protocol for receiving the result string. This is how for example a UIImagePickerController and all other Cocoa controllers for user input does it. An example:

@protocol MyTextInputDelegate;

@interface MyTextInput : UIViewController {
  id<MyTextInputDelegate> textInputDelegate;
}
@property(nonatomic,assign) id<MyTextInputDelegate> textInputDelegate;
// More interfaces here...
@end

@protocol MyTextInputDelegate
-(void)textInput:(MyTextInput*)textInput didInputText:(NSString*)text;
@end

Then let the class that needs the result conform to the MyTextInputDelegate protocol, and set it as the delegate. This way you avoid global variables, and there is no question of who owns the text object.

The other method would be to send the result as a NSNotification. This is slightly harder setup, and should only be used if you want a loose connection between the sender and the receiver.

Upvotes: 2

Eimantas
Eimantas

Reputation: 49344

If these are application settings you should consider using NSUserDefaults. If it's constants, you should define them in prefix header file.

Upvotes: 3

Related Questions