Static Global variable in Obj-C?

2019-08-28 15:03发布

// 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条回答
▲ chillily
2楼-- · 2019-08-28 15:37

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";
查看更多
登录 后发表回答