如何在Objective-c中使用类变量,如“MyClassName.var”?

时间:2022-09-07 20:12:50

I want to declare static-class variables in objective-c class and want to use them directly using class name like

我想在objective-c类中声明静态类变量,并希望使用类名直接使用它们

E.g

例如

having a class named "Myclassname" and variable "Var"

有一个名为“Myclassname”和变量“Var”的类

and want access this variable like this....

并希望像这样访问这个变量....

Myclassname.Var=@"hi";

Myclassname.Var = @ “喜”;

I dont want to use getters and setters.

我不想使用getter和setter。

Any help please?

有什么帮助吗?

2 个解决方案

#1


1  

Variables aren't accessed using the . syntax - those are getters and setters. Your only option, as @bbarnhart points out, is to manually declare class getters and setters.

使用不访问变量。语法 - 那些是getter和setter。正如@bbarnhart所指出的,你唯一的选择就是手动声明类getter和setter。

@interface Myclassname

+(NSString *)var;
+(void)setVar:(NSString *)newVar;

@end

And implement these methods to access/set the backing static variable.

并实现这些方法来访问/设置后备静态变量。

This isn't really a good idea, anyway, and doesn't jive with Objective-C style. You should consider using a singleton and properties, instead.

无论如何,这不是一个好主意,并且不符合Objective-C风格。您应该考虑使用单例和属性。

#2


0  

I don't see why you can't use the -> syntax like this:

我不明白为什么你不能像这样使用 - >语法:

Myclassname->var = @"Hi";

#1


1  

Variables aren't accessed using the . syntax - those are getters and setters. Your only option, as @bbarnhart points out, is to manually declare class getters and setters.

使用不访问变量。语法 - 那些是getter和setter。正如@bbarnhart所指出的,你唯一的选择就是手动声明类getter和setter。

@interface Myclassname

+(NSString *)var;
+(void)setVar:(NSString *)newVar;

@end

And implement these methods to access/set the backing static variable.

并实现这些方法来访问/设置后备静态变量。

This isn't really a good idea, anyway, and doesn't jive with Objective-C style. You should consider using a singleton and properties, instead.

无论如何,这不是一个好主意,并且不符合Objective-C风格。您应该考虑使用单例和属性。

#2


0  

I don't see why you can't use the -> syntax like this:

我不明白为什么你不能像这样使用 - >语法:

Myclassname->var = @"Hi";