如何在目标c中访问和更新单例类的类变量?

时间:2017-01-18 11:27:51

标签: ios objective-c singleton

声明如下: - (CalendarSetting.h)

#import <Foundation/Foundation.h>

@interface CalendarSetting : NSObject

@property(class,strong,nonatomic)NSDate *currentDate;

@end

//实现是:-( CalendarSetting.m)

+(void)set_member_var:(NSDate *)fordate
{

[CalendarSetting setCurrentDate:fordate];

}

+(void)setCurrentDate:(NSDate *)currentDate
{
    CalendarSetting.currentDate=currentDate;
    return;
}

现在这个流导致了setCurrentDate的递归调用,我怎样才能在同一个.m文件或​​任何其他类中读取currentDate的值?

1 个答案:

答案 0 :(得分:0)

@implementation 之后,您需要为类属性声明一个后备存储 -

@implementation CalendarSetting
static NSDate *_currentDate = nil;
// continue for other class vars...

访问者 分配返回 静态 变量。< / p>

示例setter -

+(void)setCurrentDate:(NSDate *)currentDate {
      _currentDate = [currentDate copy];
}

示例getter用于读取currentDate -

+(NSDate*)currentDate {
     return _currentDate; // can return nil
}