Objective-C 中的静态 NSStrings [英] static NSStrings in Objective-C

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

问题描述

我经常在类实例方法中看到这样的代码片段:

I frequently see a code snippet like this in class instance methods:

static NSString *myString = @"This is a string.";

我似乎无法弄清楚为什么会这样.这是否只是限于方法范围内的#define 的 objc 等价物?我(认为)我了解变量的静态性质,但更具体地说是关于 NSStrings,为什么它没有被分配、初始化?

I can't seem to figure out why this works. Is this simply the objc equivalent of a #define that's limited to the method's scope? I (think) I understand the static nature of the variable, but more specifically about NSStrings, why isn't it being alloc'd, init'd?

谢谢~

推荐答案

刚刚偶然发现了相同的 static NSString 声明.我想知道这个静态魔法究竟是如何工作的,所以我读了一点.我只会解决你问题的静态部分.

Just stumbled upon the very same static NSString declaration. I wondered how exactly this static magic works, so I read up a bit. I'm only gonna address the static part of your question.

根据K&R,C 中的每个变量都有两个基本属性:type(例如 float)和 存储类(auto、register、static、extern、typedef).

According to K&R every variable in C has two basic attributes: type (e.g. float) and storage class (auto, register, static, extern, typedef).

static 存储类根据是否使用有两种不同的效果:

The static storage class has two different effects depending on whether it's used:

  • 在代码块内部(例如在函数内部),
  • 在所有块之外(与函数处于同一级别).

一个变量块内没有声明它的存储类,默认情况下被认为是自动的(即它是本地的).一旦块退出,它就会被删除.当您将自动变量声明为静态时,它将在退出时保持其值.当代码块再次被调用时,该值仍然存在.

A variable inside a block that doesn't have it's storage class declared is by default considered to be auto (i.e. it's local). It will get deleted as soon as the block exits. When you declare an automatic variable to be static it will keep it's value upon exit. That value will still be there when the block of code gets invoked again.

全局变量(与函数在同一级别声明)始终是静态的.将全局变量(或函数)显式声明为静态会将其范围限制为仅单个源代码文件.它不会被访问,也不会与其他源文件发生冲突.这称为内部链接.

Global variables (declared at the same level as a function) are always static. Explicitly declaring a global variable (or a function) to be static limits its scope to just the single source code file. It won't be accessible from and it won't conflict with other source files. This is called internal linkage.

如果您想了解更多信息,请阅读内部和外部C中的链接.

If you'd like to find out more then read up on internal and external linkage in C.

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

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