Static Global variable in Obj-C?

隐身守侯 提交于 2019-12-24 19:39:57

问题


// in ClassA.h  
static NSString *globalStr = @"HelloWorld";

@interface ClassA  
    ...  
@end

// in ClassB.h  
#include "ClassA.h"

// in ClassB.m  
...  
NSLog(@"The global string: %@", globalStr);
...

In C++, "static" should mean the variable or function has a internal linkage.
But it is used to share the variable in this case, error will occur without the static keyword.

I'm confused, could someone tell me the concept behind?
Thanks!


回答1:


static means exactly the same thing in Objective-C that in means in C - it has internal linkage and static storage duration. You get an error without the static in this case because you will have a duplicate symbol globalStr in each object whose source code included ClassA.h. You're not sharing anything - you're getting a new copy of globalStr for each compilation unit.

Don't put object definitions in your headers and you'll be better off. If you want a single global string, you need to put

extern NSString *globalStr;

In ClassA.h, and define it in exactly one implementation file as:

NSString *globalStr = @"HelloWorld";


来源:https://stackoverflow.com/questions/3055641/static-global-variable-in-obj-c

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