2012-06-25 44 views
11

我知道它支持自动变量,但类变量呢?Objective-C是否支持类变量?

+0

[iPhone上的Objective C中的静态字符串变量]的可能重复(http://stackoverflow.com/questions/980083/static-string-variable-in-objective-c-on-iphone) –

+0

http ://stackoverflow.com/questions/1063229/objective-c-static-class-level-variables –

回答

23

该语言不支持类变量。您可以在实现的编译单元中使用全局变量static实现特定于类的状态。

在报头(h文件):

@interface MyClass : NSObject 
+(int)val; 
@end 

在实施(.m文件):

static int val = 123; 

@implementation MyClass 
+(int)val {return val;} 
@end 

用法:

if ([MyClass val] > 100) ... 
+0

这种语言必须销毁) – user924

+0

@ user924对于所有实际用途,语言已经死亡。 [你错过了备忘录吗?](https://developer.apple。com/swift /) – dasblinkenlight

+0

我知道,但我需要使用OpenCV,在这里我们再次使用Objective-C – user924

4

ObjC类变量是纯旧的静态变量。

Foo.m

Foo.mm

namespace { 
    int foo = 0; 
} 

但还有另一种模式,如果你想受益

static int foo = 0; 

或者,你可以,如果你使用ObjC++使用C++匿名命名空间来自物业的优势:

Foo.h

@interface FooShared 

@property (atomic, readwrite, strong) Foo* foo; 

@end 

@interface Foo 

+ (FooShared*) shared; 

@end 

Foo.m

@implementation FooShared 
@end 

static fooShared* = nil; 

@implementation Foo 

+ (FooShared*) shared 
{ 
    if (fooShared == nil) fooShared = [FooShared new]; 

    return fooShared; 
} 

@end 

somewhere.m

Foo* foo …; 
foo.shared.foo = …; 

它可能看起来有点大材小用,但它是一个有趣的解决方案。您对实例属性和“类”属性使用相同的构造和语言功能。需求时的原子性,需要时的访问器,调试,断点...甚至是继承。

创意思维可以找到其他方法来做到这一切我想。 :)但你几乎覆盖了这些选项。

0
@property (class, nonatomic, copy) NSString *someStringProperty; 

但是你必须提供getter和setter

从Xcode的8发布说明: 的Objective-C现在支持类属性,这与雨燕特性互操作。它们被声明为:@property(class)NSString * someStringProperty ;.他们从未合成过。 (23891898)