1

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

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

+ (id)sharedTimeFormat;
@end

这是 .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

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

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

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

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

4

1 回答 1

5

您不想使用alloc init. 有了这个单例,所有对它的引用都应该通过它的sharedTimeFormat方法,init如果需要,它将返回对象,否则将返回单例实例。

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

于 2013-12-31T18:34:20.067 回答