0
爲了全局操作的目的,我已經在應用程序委託中聲明瞭一些字符串屬性。iPhone SDK:NSUserDefaults無法正常工作
問題是寫入的值與正在讀取的值不同。當我將調試消息打印出來時,它就是我們熟悉的數據。它幾乎看起來像被緩存。
代碼聲明:NSUserDefaults的與
//globals
NSUserDefaults *options;
NSString *strUserLogin;
NSString *strTransKey;
NSString *strBizName;
NSString *strSwitchTesting;
NSString *strDate;
NSString *strTotalAmount;
NSString *strTopMessage;
NSString *strBottomMessage;
NSString *strTransType;
NSString *strMerchantName;
NSString *strCustomerEmail;
NSString *strMerchantEmail;
@property(nonatomic,retain) NSUserDefaults *options;
@property(nonatomic,retain) NSString *strUserLogin;
@property(nonatomic,retain) NSString *strTransKey;
@property(nonatomic,retain) NSString *strBizName;
@property(nonatomic,retain) NSString *strSwitchTesting;
@property(nonatomic,retain) NSString *strDate;
@property(nonatomic,retain) NSString *strTotalAmount;
@property(nonatomic,retain) NSString *strTopMessage;
@property(nonatomic,retain) NSString *strBottomMessage;
@property(nonatomic,retain) NSString *strTransType;
@property(nonatomic,retain) NSString *strMerchantName;
@property(nonatomic,retain) NSString *strCustomerEmail;
@property(nonatomic,retain) NSString *strMerchantEmail;
加載全局變量:
[NSUserDefaults resetStandardUserDefaults];
options = [NSUserDefaults standardUserDefaults];
if(options)
{
strUserLogin = [options stringForKey:@"UserLogin"];
strTransKey = [options stringForKey:@"TransKey"];
strBizName = [options stringForKey:@"BizName"];
strSwitchTesting =[options stringForKey:@"SwitchTesting"];
//str date
//total amount
strTopMessage =[options stringForKey:@"MessageTop"];
strBottomMessage =[options stringForKey:@"MessageBottom"];
//trans type
strMerchantName = [options stringForKey:@"BizName"];
//customer email
strMerchantEmail =[options stringForKey:@"MerchantEmail"];
}
else {
NSLog(@"applicationDidFinishLaunching: Error reading config file.");
}
代碼來設置全局變量回NSUserDefaults的:
//save to disk preferences
[options setObject: txtUserLogin.text forKey:@"UserLogin"];
[options setObject: txtTransKey.text forKey:@"TransKey"];
[options setObject: txtBizName.text forKey:@"BizName"];
[options setObject: txtMerchantEmail.text forKey:@"MerchantEmail"];
[options setObject:txtMsgTop.text forKey:@"MessageTop"];
[options setObject:txtMsgBottom.text forKey:@"MessageBottom"];
if(switchTesting.on)
{
[options setObject:@"ON" forKey:@"SwitchTesting"];
}
else
{
[options setObject:@"OFF" forKey:@"SwitchTesting"];
}
//this is the magic sauce
[options synchronize];