Reputation: 4389
I need to create an NSString, so I can set its value in one class and get it in another. How can I do it?
Upvotes: 6
Views: 8541
Reputation: 1160
if you write:
NSString *globalString = @"someString";
anywhere outside a method, class definition, function, etc... it will be able to be referenced anywhere. (it is global!)
The file that accesses it will declare it as external
extern NSString *globalString;
This declaration signifies that it is being accessed from another file.
Upvotes: 10
Reputation: 109
Global NSString Variable for Complete iPhone Project/Apps
For Declare/Define/Use a global variable follow these easy steps:-
Create a NSObject File with named "GlobalVars.h and .m" or as u wish
Declare your global variable in GlobalVars.h file after #import and before @implementation like-
extern NSString *Var_name;
initialize it in GlobalVars.m file after #import and before @implementation like-
NSString *Var_name = @"";
Define its property in AppDelegate.h File
@property (nonatomic, retain) NSString *Var_name;
synthesize it in AppDelegate.m File like-
@synthesize Var_name;
Now where you want to use this variable (in .m file) just import/inclue GlobalVars.h file in that all .h files, and you can access easily this variable as Globally.
Carefully follow these Steps and it'll work Surely.
Upvotes: 6
Reputation: 46
Remember that you should keep memory allocation and freeing in mind. This is not the same thing as a global int value - you need to manage the memory with any NSObject.
Repeatedly just setting the global to new strings will leak. Accessing through threads will create all manner of issues. Then there is shutdown where the last string will still be around.
Upvotes: 2
Reputation: 8535
I think you should use a singleton. A good article that discusses this is Singletons, AppDelegates and top-level data.
Additional information on a singleton class is at MVC on the iPhone: The Model
Upvotes: 0
Reputation: 36497
If you're creating a global NSString
variable, you should use probably use a class method.
In MyClass.h
:
@interface MyClass : NSObject {}
+ (NSString *)myGlobalVariable;
+ (void)setMyGlobalVariable:(NSString *)val;
@end
In MyClass.m
:
@implementation MyClass
NSString *myGlobalVariable = @"default value";
+ (NSString *)myGlobalVariable {
return myGlobalVariable;
}
+ (void)setMyGlobalVariable:(NSString *)val {
myGlobalVariable = val;
}
@end
Upvotes: 3
Reputation: 17189
Make it a global variable.
In one file in global scope:
NSMutableString *myString = @"some funny string";
In the other file:
extern NSMutableString *myString;
Upvotes: 6