在objective-c中声明静态变量的位置? [英] Where to declare a static variable in objective-c?

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

问题描述

我在objective-c中对静态变量进行了一些研究,我发现人们在不同的地方声明了静态变量,这让我很困惑。

I did some research about static variables in objective-c and I found people declare static variables in different places which made me really confused.


  1. 对于以下代码,我可以在实现之外放置静态NSUInteger计数器; 吗? (在我的#importxxx.h之后)

  1. For the following code, can I put static NSUInteger counter;outside of the implementation? (Right after my #import "xxx.h")

我可以放置静态NSUInteger计数器; 在+ initialize类方法里面?

Can I put static NSUInteger counter;inside of +initialize class method?

我可以将静态NSUInteger计数器; 放入实例方法吗?

Can I put static NSUInteger counter; into a instance method?

最重要的是,有什么区别以及如何选择宣告它们的位置?

Most importantly, what are the differences and how to choose where to declare them?

谢谢!

@implementation MyClass

static NSUInteger counter;

+(void)initialize {
    if (self == [MyClass class]) {
        counter = 0;
    }
}

@end


推荐答案

您提供的版本中只有两个版本。在实现块内部或外部声明它们之间没有区别,因为静态变量不与类关联,而是与文件本身关联。由于同样的原因,在类方法或实例方法中声明它们之间也没有区别。

There are really only two versions out of the ones you provided. There is no difference between declaring them inside or outside the implementation block because static variables are not associated with the class but the file itself. There is also no difference between declaring them in a class method or instance method for the same reason.

在方法内部声明它们之间的唯一区别是,如果它在一个方法中声明,它只能从同一个方法中访问。

The only difference between declaring them inside a method or not, is that if it is declared inside a method, it is only ever accessible from within that same method.

最好在最具体的范围内声明一个变量,你可以这样做在没有意外导致错误的地方使用它是没有风险的。如果您只需要访问方法中的静态变量,请在那里声明它。否则在文件中的任何其他位置声明它(在您需要的位置上方)。你究竟放在哪里纯粹是一种风格的东西。我个人更喜欢它是在导入之后但在@implementation之前(如果我添加一个,则为类扩展)。

It is always best to declare a variable inside the most specific scope that you can so there is no risk of using it somewhere unintended causing bugs. If you only need to have access to the static variable inside a method, declare it there. Otherwise declare it anywhere else in the file (above where you need it). Where exactly you put it is purely a style thing at that point. I personally prefer it be after the imports but before the @implementation (and class extension if I add one).

这篇关于在objective-c中声明静态变量的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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