Global NSString

梦想的初衷 提交于 2019-12-04 22:51:15

问题


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?


回答1:


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.




回答2:


Make it a global variable.

In one file in global scope:

NSMutableString *myString = @"some funny string";

In the other file:

extern NSMutableString *myString;



回答3:


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.



回答4:


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



回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/2722517/global-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!