ios - 如何声明静态变量?

use*_*531 7 iphone variables static objective-c ios

在C#中声明的静态变量如下:

private const string Host = "http://80dfgf7c22634nbbfb82339d46.cloudapp.net/";
private const string ServiceEndPoint = "DownloadService.svc/";
private const string ServiceBaseUrl = Host + ServiceEndPoint;
public static readonly string RegisteredCourse = ServiceBaseUrl + "RegisteredCourses";
public static readonly string AvailableCourses = ServiceBaseUrl + "Courses";
public static readonly string Register = ServiceBaseUrl + "Register?course={0}";
Run Code Online (Sandbox Code Playgroud)

如何在另一个类中调用此静态变量?

Bha*_*vin 12

答:使用static关键字.

语法:( 根据Abizern的评论static ClassName *const variableName = nil;更新[已添加const])


更新的原因(根据"Till"的注释): static当在函数/方法中的变量上使用时,即使在保留该变量的范围时也将保留其状态.当在任何函数/方法之外使用时,它将使该变量对其他源文件不可见 - 只有在任何函数/方法之外使用时,它才会在该实现文件中可见.因此const,static有助于编译器相应地优化它.

如果你需要更多关于使用constwith的解释static,我在这里找到了一个很棒的链接:const static.


使用:

您可能已经在tableview的委托中看到过使用"static"关键字- cellForRowAtIndexPath:

static NSString *CellIdentifier = @"reuseStaticIdentifier";

  • 我会写`static NSString*const staticURL = @"something";` (2认同)
  • @Abizern:你能解释一下`const`背后的原因吗? (2认同)
  • @Vin该变量在运行时永远不会被更改,因此const可以帮助编译器相应地优化它. (2认同)

Max*_*iel 5

static NSString *aString = @""; // Editable from within .m file
NSString * const kAddressKey = @"address"; // Constant, visible within .m file

// in header file
extern NSString * const kAddressKey; // Public constant. Use this for e.g. dictionary keys.
Run Code Online (Sandbox Code Playgroud)

据我所知,公共静态不是Objective-C的内置功能.您可以通过创建一个返回静态变量的公共类方法来解决此问题:

//.h
+ (NSString *)stringVariable;

//.m
static NSString * aString;
+ (NSString *)stringVariable
{
    return aString;
}
Run Code Online (Sandbox Code Playgroud)

大多数静态对象在编译时无法初始化(我认为实际上只有字符串).如果你需要初始化它们,你可以在+ (void)initialize方法中这样做,只要首次引用该类,就会懒惰地调用它.

static UIFont *globalFont;
+ (void)initialize
{
    // Prevent duplicate initialize http://www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading-and-initialization.html
    if (self == [ClassName class]) {
        globalFont = [UIFont systemFontOfSize:12];
    }
}
Run Code Online (Sandbox Code Playgroud)