@implementation中声明的变量

And*_*rew 3 objective-c

我正在处理一本书中的代码清单,它有一对变量(特别是NSString*)在@implementation中声明和初始化,而不是@interface,但在任何方法体之外.我以前没见过这个,我想知道这在范围上有什么不同等等.

我已经快速浏览了Objective C Programming Language,但我看不出有什么描述它有什么影响.

谢谢

安迪

Phi*_*ert 8

在@implementation中声明的变量具有全局范围.

如果将它们声明为"静态",则只能从同一源文件中的方法中看到它们.

所以:

@implementation MyClass

NSString *myString; // global scope, and accessible by all code in your project
Run Code Online (Sandbox Code Playgroud)

要么

@implementation MyClass

static NSString *myString; // global scope, but only accessible by code 
                           // in this source file
Run Code Online (Sandbox Code Playgroud)