我有一个应用程序,我正在使用单身人士;这是.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中设置singleton初始值的代码:
// 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'
我不明白为什么值保持设定?我错过了什么吗?
答案 0 :(得分:4)
这是因为您要为NSNumber*
分配零。您需要分配[NSNumber numberWithInt:0]
或@0
,否则整数将被解释为地址:
sharedInstance.globalServicesType = @0; // <<== Here