2013-08-17 49 views
-1

我有一個應用程序,我使用的是單身人士;這裏是在.h文件中的代碼:爲什麼我的Singleton沒有維持它的設定值?

@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

這是因爲您將零分配給NSNumber*。您需要指定[NSNumber numberWithInt:0]@0,否則該整數解釋爲地址:

sharedInstance.globalServicesType = @0; // <<== Here 
相關問題