英文:
Access static class variables in Objective-C
问题
我想在类外部使用类变量。
通过“外部”,我指的是在我实例化类的主要函数中。
@interface Class: NSObject
static int var_class; // 类变量
{
int var_object; // 对象变量
}
@end
@implementation Class
@end
为了访问var_object
,也就是对象变量,我们可以使用以下方式:
int main(void)
{
Class *object = [Class new];
// 访问变量
object->var_object;
(*object).var_object;
return 0;
}
我以为我可以以同样的方式访问var_class
,也就是类变量。
但是它们都没有起作用(无法编译)。
Class.var_class;
// -> 生成错误:在类'TheClass'中找不到setter/getter 'count'
Class->var_class;
// -> 生成错误:预期'.'在'- >'标记之前
我如何获取/设置类变量的值?
声明一个函数是访问类变量的方法,但我想要更简单的方法。
@interface Class: NSObject
static int var_class; // 类变量
+(int) get;
+(void) set: (int) val;
@end
@implementation Class
+(int) get
{
return var_class;
}
+(int) set: (int) val
{
var_class = val;
}
@end
英文:
I would like to use class variables outside of the class.
By 'outside', I mean the main function where I instantiate the class.
@interface Class: NSObject
static int var_class; // Class variable
{
int var_object; // Object variable
}
@end
@implementation Class
@end
In order to access var_object
, the object variable, we use:
int main(void)
{
Class *object = [Class new];
// Access to the variable
object->var_object;
(*object).var_object;
return 0;
}
I thought I could access var_class
, the class variable, in the same way.
But none of them worked. (Unable to compile)
Class.var_class;
// -> Generates error: could not find setter/getter for 'count' in class 'TheClass'
Class->var_class;
// -> Generates error: error: expected '.' before '->' token
How can I get/set the class variable's value?
Declaring a function is the way to access class variables, but I want it simpler.
@interface Class: NSObject
static int var_class; // Class variable
+(int) get;
+(void) set: (int) val;
@end
@implementation Class
+(int) get
{
return var_class;
}
+(int) set: (int) val
{
var_class = val;
}
@end
答案1
得分: 0
Objective-C 中没有静态类变量,因此你不能期望像 Class.var_class
这样的东西。这就是为什么你最后的提议是正确的,并且通常被采用的原因。请参考:https://stackoverflow.com/questions/11187530/does-objective-c-support-class-variables。
----EDIT----
Objective-C 中添加了一些新的构造,参见Objective-C类属性。因此,语法是允许的,但没有自动合成。
英文:
There is no static class variables in Objective-C, thus you can't expect something like Class.var_class
. This is why your last proposition is a correct one, and commonly adopted. See, https://stackoverflow.com/questions/11187530/does-objective-c-support-class-variables.
----EDIT----
Some new constructions were added to Objective-C, see Objective-C Class Properties. Thus syntax is admitted, while there is no automatic synthesis.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论