我想在應用程序關閉後使用NSUserDefaults保存兩個變量。一個是第一個引導和另一個顯示。準備不好的代碼 -NSUserDefaults不加載我想要的數字
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults]; //Here is where it is supposed to be loading the firstBoot variable to check whether or not it is the first boot
NSInteger boot = [defaults1 integerForKey:@"firstBoot"];
firstBoot = boot; //Sort of pointless variable swapping
if (firstBoot == 0) //Detects if isn't first boot, checks whether or not showAgain is yes or no (1=yes, 0=no)
{
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSInteger boot = [defaults1 integerForKey:@"firstBoot"];
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
NSInteger show = [defaults2 integerForKey:@"showAgain"];
firstBoot = boot; //More var swapping
showAgain = show; //^^
}
else
{
firstBoot = 1; //If it is the first boot, or the variable wasn't 0, it sets them both to 1.
showAgain = 1;
}
if ((firstBoot == 1) || (showAgain == 1)) //Checks if its the firstBoot or showAgain is set to yes
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Check the 'About' tab for help!" //Displays alert
message:@""
delegate:self
cancelButtonTitle:@"Don't show again"
otherButtonTitles:@"OK", nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"firstboot and showagain != 1" //Displays alert if it isn't the first boot, or isn't 1 and showAgain isn't set to yes(1).
message:@""
delegate:self
cancelButtonTitle:@"wrong"
otherButtonTitles:@"OK", nil];
[alert show];
}
}
Alert-
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == [alertView cancelButtonIndex])
{
showAgain = 0; //If user clicks "Don't show again", set showAgain to off(0) and tell it it isn't the first boot anymore
firstBoot = 0;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setInteger:0 forKey:@"firstBoot"]; //Hopefully stores firstBoot as 0
[defaults1 synchronize];
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
[defaults2 setInteger:0 forKey:@"showAgain"]; //Again storing showAgain as 0
[defaults2 synchronize];
}
}
第一個提醒應彈出你運行應用程序的第一次,而第二個是一個調試器的佔位符,並應每次運行在第一次之後。對我來說,第二個是先運行,告訴我,第一個引導和showAgain!= 1。
您可以將BOOL存儲爲默認值而不是數字。 – Abizern