Knodel
Knodel

Reputation: 4389

Global NSString

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

Answers (6)

samfu_1
samfu_1

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

Global NSString Variable for Complete iPhone Project/Apps

For Declare/Define/Use a global variable follow these easy steps:-

  1. Create a NSObject File with named "GlobalVars.h and .m" or as u wish

  2. Declare your global variable in GlobalVars.h file after #import and before @implementation like-

    extern NSString *Var_name;

  3. initialize it in GlobalVars.m file after #import and before @implementation like-

    NSString *Var_name = @"";

  4. Define its property in AppDelegate.h File

    @property (nonatomic, retain) NSString *Var_name;

  5. synthesize it in AppDelegate.m File like-

    @synthesize Var_name;

  6. 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.

  7. Carefully follow these Steps and it'll work Surely.

Upvotes: 6

Andrew Hooke
Andrew Hooke

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

Sharjeel Aziz
Sharjeel Aziz

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

John Calsbeek
John Calsbeek

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

bastibe
bastibe

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

Related Questions