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];