ios – 如何声明静态variables?

在C#中声明的静态variables是这样的:

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}"; 

如何在另一个类中调用这个静态variables?

答:使用static关键字。

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


更新原因(根据“Till”的注释) :当在一个函数/方法中的variables上使用static时,即使保留了该variables的作用域,它也会保留它的状态。 当在任何函数/方法之外使用时,它将使该variables对其他源文件不可见 – 只有当在任何函数/方法之外使用时,才会在该实现文件中可见。 因此, staticconst有助于编译器相应地优化它。

如果你需要更多关于static使用const解释,我在这里find了一个漂亮的链接: const static 。


使用:

你可能已经看到在你的tableview的委托中使用“static”关键字- cellForRowAtIndexPath:

static NSString *CellIdentifier = @"reuseStaticIdentifier";

 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 eg dictionary keys. 

据我所知,公共静力学不是Objective-C的内置function。 你可以通过创build一个返回静态variables的公共类方法来解决这个问题:

 //.h + (NSString *)stringVariable; //.m static NSString * aString; + (NSString *)stringVariable { return aString; } 

大多数静态对象不能在编译时初始化(我认为实际上只有string)。 如果你需要初始化它们,你可以在+ (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]; } } 

Objective C是C / C ++的超级集合,因此对于静态它遵循C ++ / C约定,您应该可以使用它

 static <<datatype>> <<variableName>> = initialization 

希望你能这样试试,你有没有错误,如果是的话,请在你的问题中增加一些清晰度

如果这种情况与NSString使用以下,

 static NSString *pString = @"InitialValue"; 

如果你不得不在你的代码中修改NSString ,确保它必须是NSMutableString

希望这是帮助…