ObjectiveC中的静态变量

ObjectiveC中的静态变量

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

问题描述

静态变量是在编译时静态分配的变量.我的疑问是静态声明某些变量的目的是什么?到目前为止,我没有在代码中使用任何静态变量.来自苹果代码 http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.html在 securityWrapper.m 中,有一行

Static variables are variables allocated statically at compile time. My doubt is for what purpose some variables are declared statically? I didn't have used any static variable in my code till now. From the apple code http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.htmlin securityWrapper.m, there is a line

static SecKeyWrapper * __sharedKeyWrapper = nil;

这里静态分配__sharedKeyWrapper有什么用?

what is the use of statically allocating __sharedKeyWrapper here?

我在这么多代码中看到了静态关键字的使用.所以请解释一下 static 关键字的用途和好处.

I have seen the use of static key word in so many codes. So kindly explain the use and benefits when static keyword.

提前致谢.

推荐答案

该文件全局是一个 singleton,用于共享一个类的实例.

That file global is a singleton, used for sharing an instance of a class.

它在 Objective-C 中是静态的原因是 内部链接.实际上,这意味着在声明它的文件之外无法看到该变量.如果另一个文件声明了同名的变量,则它们是两个不同的变量.

The reason it's static in Objective-C is internal linkage. In practice, this means the variable can not be seen outside the file it is declared in. If another file declares a variable with the same name, they're two different variables.

请记住,Objective-C 实例的工作方式,实际上不会自动分配实例.相反,您有一个指向该实例的指针.代码仍然必须执行以下操作:

Keep in mind that the way Objective-C instances work, the instance won't actually be allocated automatically. Rather, you have a pointer to the instance. The code will still have to do something like:

if ( !_sharedKeyWrapper ) {
    _sharedKeyWrapper = [[SecKeyWraper alloc] initBlahBlah];
}

查看更多链接.

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

08-22 12:44