-1

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

@interface SingletonServicesType : NSObject  {
}
@property (nonatomic, retain) NSNumber *globalServicesType;

+ (id)sharedInstance;
@end

这是 .m 文件中的代码:

//-------------------------------------------
//--  SingletonServicesType
@implementation SingletonServicesType  {  

}

@synthesize globalServicesType;  //  rename

//--  sharedInstance  --
+ (id)sharedInstance  {

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) {
    globalServicesType = [[NSNumber alloc] init];
}
return self;
}

@end

这是我在 AppDelegate.m 中设置单例初始值的代码:

    //  set services
SingletonServicesType *sharedInstance = [SingletonServicesType sharedInstance];  //  initialize
if(preferenceData.aServicesType == nil)  {
    sharedInstance.globalServicesType = 0;  //  (0) is the default
    preferenceData.aServicesType = 0;  //  here too...
    [localContext MR_saveNestedContexts];  //  save it...
}
else
    sharedInstance.globalServicesType = preferenceData.aServicesType;  //  0 = default (nails), 1 = custom

NSLog(@"\n\n1-sharedInstance.globalServicesType: %@", [NSNumber numberWithInt: (sharedInstance.globalServicesType)]);  //  shows a value of '0'

当我立即检查另一个类中单例的值时,它是'null'!这是代码:

    SingletonServicesType *sharedInstance = [SingletonServicesType sharedInstance];  //  initialize
NSLog(@"\n\n2-sharedInstance.globalServicesType: %@", sharedInstance.globalServicesType);  //  shows a value of 'null'

我不明白为什么该值保持设置?我错过了什么吗?

4

1 回答 1

4

这是因为您将零分配给NSNumber*. 您需要分配[NSNumber numberWithInt:0]or @0,否则整数将被解释为地址:

sharedInstance.globalServicesType = @0; // <<== Here
于 2013-08-17T16:55:48.090 回答