ios - 如何声明静态变量? [英] ios - How to declare static variable?
问题描述
在C#中声明的静态变量如下所示:
Static Variable declared in C# like this :
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}";
如何在另一个类中调用此静态变量?
How to call this static variable in another class ?
推荐答案
答案:使用 static
关键字。
语法: static ClassName * const variableName = nil;
(已更新 [添加 const
] 根据评论 Abizern )
更新原因(根据Till的评论):
static
当在函数/方法中的变量上使用时,即使在保留该变量的范围时也将保留其状态。当在任何函数/方法之外使用时,它将使该变量对其他源文件不可见 - 只有在任何函数/方法之外使用时,它才会在该实现文件中可见。
因此带有 static
的 const
可帮助编译器相应地优化它。
Reason for update ( As per the comments by "Till " ) :
static
when being used on a variable within a function/method will preserve its state even when the scope of that variable is left. When being used outside any function/method, it will make that variable invisible to other source files - it will be visible within that implementation file only when being used outside any function/method.
Hence a const
with static
helps the compiler to optimize it accordingly.
如果你需要更多关于 const
使用 static
的解释,我找到了一个漂亮的链接到这里: const static 。
If you need more explanation on use of const
with static
, I found one beautiful link here : const static.
使用:
您可能已经看到在您的静态关键字中使用了tableview的委托 - cellForRowAtIndexPath:
You might have seen the use of "static" keyword in your tableview's delegate - cellForRowAtIndexPath:
static NSString * CellIdentifier = @reuseStaticIdentifier;
这篇关于ios - 如何声明静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!