如何在目标C中设置类属性? [重复]

问题描述 投票:0回答:1

如何设置可在整个应用程序中以及从目标C中的其他类访问的类属性?

注意:我知道这里还有其他答案,但是大多数答案已经过时或被撕裂! 11年前提出了标记为重复的问题...!

最近,我有一个项目更深入地研究了这个主题,我想向您提供一些代码示例,这些示例可能会对此处的人有所帮助。这也是我自己的某种信息存储方式:)

objective-c class variables class-method class-variables
1个回答
0
投票

自Xcode 8起,您就可以使用“ class”标识符在YourClass的头文件中定义类属性:

@interface YourClass : NSObject

@property (class, strong, nonatomic) NSTimer *timer;

@end

要在实现的类方法中使用类属性,您需要为类属性分配一个静态实例变量。这使您可以在类方法中使用此实例变量(类方法以“ +”开头)。

@implementation YourClass

static NSTimer *_timer;

您必须为class属性创建getter和setter方法,因为它们不会自动合成。

+ (void)setTimer:(NSTimer*)newTimer{
    if (_timer == nil)
    _timer = newTimer;
}

+ (NSTimer*)timer{
    return _timer;
}

// your other code here ...

@end

现在您可以使用以下语法从整个应用程序和其他方法访问class属性-以下是一些示例:

NSTimeInterval seconds = YourClass.timer.fireDate.timeIntervalSinceNow;

[[YourClass timer] invalidate];

您将始终将消息发送到同一对象,多个实例都不会出现问题!

请在此处找到Xcode 11示例项目:GitHub sample code

© www.soinside.com 2019 - 2024. All rights reserved.