Obj-C中的静态全局变量? [英] Static Global variable in Obj-C?

查看:121
本文介绍了Obj-C中的静态全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //在ClassA.h中
static NSString * globalStr = @HelloWorld;

@interface ClassA
...
@end

//在ClassB.h中
#includeClassA.h

//在ClassB.m中
...
NSLog(@全局字符串:%@,globalStr);
...

在C ++中,static应该表示变量或函数具有内部联动。

但在这种情况下它用于共享变量,如果没有static关键字,就会发生错误。

我很困惑,有人能告诉我背后的概念吗?

谢谢!

static ,你会得到一个错误,因为在每个对象的源代码中都有一个重复的符号 globalStr 包括 ClassA.h 。你不是共享的任何东西 - 你为每个编译单元获得一个新的 globalStr 副本。



不要将对象定义放在标题中,那样会更好。如果你想要一个单一的全局字符串,你需要把

  extern NSString * globalStr; 

ClassA.h 中,并定义它在中恰好有一个实现文件为:

  NSString * globalStr = @HelloWorld; 


// 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!

解决方案

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";

这篇关于Obj-C中的静态全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆