在AppDelegate中设置的Singleton在另一个类中分配时会丢失它的值

Spo*_*ude 1 singleton objective-c singleton-methods ios7

我有一个iPad应用程序,我试图使用单例.这是.h文件中的代码:

//-------------------------------------------
//--  singleton: timeFormat
@interface SingletonTimeFormat : NSObject  {
}
@property (nonatomic, retain) NSNumber *timeFormat;

+ (id)sharedTimeFormat;
@end
Run Code Online (Sandbox Code Playgroud)

这是.m文件中的代码:

//-------------------------------------------
//--  SingletonTimeFormat
@implementation SingletonTimeFormat  {

}

@synthesize timeFormat;

//--  sharedColorScheme  --
+ (id)sharedTimeFormat  {

static dispatch_once_t dispatchOncePredicate = 0;
__strong static id _sharedObject = nil;
dispatch_once(&dispatchOncePredicate, ^{
    _sharedObject = [[self alloc] init];
});

return _sharedObject;
}

-id) init {
self = [super init];
if (self) {
    timeFormat = [[NSNumber alloc] init];
}
return self;
}

@end
Run Code Online (Sandbox Code Playgroud)

我在AppDelegate中加载了值(12或24)- didFinishLaunchingWithOptions,然后当我想获取timeFormat的值时,我使用:

SingletonTimeFormat *stf = [[SingletonTimeFormat alloc]init];
if([stf.timeFormat isEqualToNumber: [NSNumber numberWithInt:12]]) {
Run Code Online (Sandbox Code Playgroud)

返回0(它在AppDelegate中设置正确,但显然当我在另一个类中执行alloc时,它会丢失它的值.显然它不起作用!(我有其他几个具有相同模式的单例,但到目前为止它们出现了工作.

这里有什么问题,我该如何解决?

Joe*_*her 5

你不想用你的单身人士来打电话alloc init.对于这个单例,所有对它的引用都应该通过它的sharedTimeFormat方法,init如果有必要,它将是对象,否则将返回单例实例.

换句话说,您似乎没有引用存储在静态sharedObject变量中的对象实例,这意味着它的存储值不一定相同.