Objective-C是否支持类变量?

Vol*_*da2 14 objective-c class-variables

我知道它支持自动变量,但类变量怎么样?

das*_*ght 30

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

在标题(.h文件)中:

@interface MyClass : NSObject
+(int)val;
@end
Run Code Online (Sandbox Code Playgroud)

在实现(.m文件)中:

static int val = 123;

@implementation MyClass
+(int)val {return val;}
@end
Run Code Online (Sandbox Code Playgroud)

用法:

if ([MyClass val] > 100) ...
Run Code Online (Sandbox Code Playgroud)

  • 这种语言必须被销毁) (8认同)

fab*_*ier 6

ObjC类变量是普通的旧静态变量.

Foo.m:

static int foo = 0;
Run Code Online (Sandbox Code Playgroud)

或者,如果使用ObjC++,则可以使用C++匿名命名空间:

Foo.mm:

namespace {
    int foo = 0;
}
Run Code Online (Sandbox Code Playgroud)

但如果您想从属性的优势中受益,还有另一种模式:

Foo.h:

@interface FooShared

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

@end

@interface Foo

+ (FooShared*) shared;

@end
Run Code Online (Sandbox Code Playgroud)

Foo.m:

@implementation FooShared
@end

static fooShared* = nil;

@implementation Foo

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

    return fooShared;
}

@end
Run Code Online (Sandbox Code Playgroud)

somewhere.m:

Foo* foo …;
foo.shared.foo = …;
Run Code Online (Sandbox Code Playgroud)

它可能看起来有点矫枉过正,但这是一个有趣的解决方案.您对实例属性和"类"属性使用相同的构造和语言功能.按需原型,需要时的访问器,调试,断点......甚至继承.

我想,创造性思维可以找到其他方法来做这一切.:)但你几乎满足于这些选项.


Ula*_*mir 5

@property (class, nonatomic, copy) NSString *someStringProperty;
Run Code Online (Sandbox Code Playgroud)

但你必须提供 getter 和 setter

来自 Xcode 8 发行说明: Objective-C 现在支持类属性,可以与 Swift 类型属性进行互操作。它们被声明为:@property (class) NSString *someStringProperty;。它们从未被合成。(23891898)