views:

178

answers:

5
+2  Q: 

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?

+4  A: 

Make it a global variable.

In one file in global scope:

NSMutableString *myString = @"some funny string";

In the other file:

extern NSMutableString *myString;
BastiBechtold
+1  A: 

if you write:

NSString *globalString = @"someSring";   

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.

samfu_1
+2  A: 

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
John Calsbeek
A: 

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

Shaji
+1  A: 

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.

Andrew Hooke