iOS:在 NSUserDefaults 中使用布尔值

发布于 2024-09-26 05:16:09 字数 323 浏览 9 评论 0原文

当加载应用程序的 rootViewController 时,我希望能够检查用户登录凭据是否已保存到 NSUserDefaults 中。

基本上,当用户加载应用程序并且他/她没有保存登录凭据时,将推送 modalAlertView,并且用户将能够适当地保存其凭据。这会将这些 UITextField 字符串保存到相应的 NSUserDefault 对象中。但是,当保存完成后,我是否可以创建一个布尔值的 NSUserDefault 对象并将值更改为 yes?

这意味着布尔值已经设置为 no,并且当用户保存其登录凭据时,它也会将布尔值更改为 yes?

When the rootViewController of my application is loaded, I want to be able to check whether or not the users login credentials have been saved to NSUserDefaults.

Basically, when the user loads the application and he/she doesn't have her login credentials saved, a modalAlertView will be pushed and the user will be able to save their credentials appropriately. This saves those UITextField strings to a respective NSUserDefault object. However, is it possible, that when this saving is done, I can create an NSUserDefault object which is a boolean and change the value to a yes?

Meaning that the boolean is already set to no, and when the user saves their login credentials, it also changes the boolean to a yes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

软糖 2024-10-03 05:16:09

您可以使用以下方式设置布尔值:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"logged_in"];
[[NSUserDefaults standardUserDefaults] synchronize];

并使用以下代码读取它:

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"logged_in"]) {
    [self displayLogin];
} else {
    [self displayMainScreen];
}

You can set your boolean by using:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"logged_in"];
[[NSUserDefaults standardUserDefaults] synchronize];

and read it by using this code:

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"logged_in"]) {
    [self displayLogin];
} else {
    [self displayMainScreen];
}
盗梦空间 2024-10-03 05:16:09

NSUserDefaults 中有一个名为 registerDefaults: 的方法。您可以使用此方法来设置应用程序的“默认值”。基本上,您创建一个包含默认键和值的NSDictionary(在您的情况下,“保存的凭据”键为“否”),然后使用registerDefaults:注册它。这通常在应用程序委托的 + (void)initialize 方法中完成,以确保您的默认值在需要之前已注册。仅当您的应用尚未替换这些值时才会使用它们。换句话说,除非您要查找的密钥不在应用程序域中,否则它们不会被使用,即用户默认从用户的 .plist 文件中读取。

另一方面,您可以只检查登录凭据,如果丢失则弹出警报。这样就无需使布尔值与登录凭据保持同步。如果您稍后提供“删除登录凭据”功能,则不必记住将布尔值设置回 NO。如果您的登录凭据保存在用户的默认值中,您可以执行以下操作:

NSString *userID = [[NSUserDefaults standardUserDefaults] stringForKey:@"userID"];
NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password"];
if (userID != nil && password != nil) {
    // Code to log user in
} else {
    // Code to pop up an alert
}

There is a method in NSUserDefaults called registerDefaults:. You use this method to set your application's "default defaults." Basically, you create an NSDictionary containing your default keys and values (in your case a NO for a "saved credentials" key), and you register it using registerDefaults:. This if often done in app delegate's + (void)initialize method to ensure that your defaults are registered before they are needed. These values only get used if your app hasn't replaced them. In other words, they won't be used unless the key you're looking for isn't in the Application Domain, i.e., the user defaults read from the user's .plist file.

On the other hand, you could just check for login credentials and pop up an alert if they're missing. This eliminates the need to keep your boolean value synchronized with the login credentials. If you later provide a "delete login credentials" capability, you won't have to remember to set the boolean back to NO. If your login credentials are saved in user's defaults, you'd do this:

NSString *userID = [[NSUserDefaults standardUserDefaults] stringForKey:@"userID"];
NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password"];
if (userID != nil && password != nil) {
    // Code to log user in
} else {
    // Code to pop up an alert
}
吹泡泡o 2024-10-03 05:16:09

Henrik P. Hessel 建议的解决方案:

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"logged_in"]) {
[self displayLogin];
} else {
[self displayMainScreen];
}

适用于您的情况,但请记住,您不应该检查此代码是否设置了某个键,因为如果它实际上已设置并设置为“NO”,你仍然会得到一个结果,就好像根本没有设置一样。相反,我会使用

if([[NSUserDefaults standardUserDefaults] objectForKey:@"logged_in"] == nil) {
    //Do something
}

This solution, suggested by Henrik P. Hessel:

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"logged_in"]) {
[self displayLogin];
} else {
[self displayMainScreen];
}

would work in your case, but bear in mind that you shouldn't check with this code if some key is set at all, because if it actually is set and set to "NO", you would still get a result as if was not set at all. Instead I would use

if([[NSUserDefaults standardUserDefaults] objectForKey:@"logged_in"] == nil) {
    //Do something
}
薄荷梦 2024-10-03 05:16:09

您不需要首先将其设置为NO,而是可以检查是否已设置密钥。如果没有,并且您的应用确定凭据已完成,则只需创建它并将其设置为YES

查看我对另一个问题的回答,了解我通常如何执行此操作。

You don't need to first set it to NO, instead you may check if a key has been set at all. If not, and if your app determines the credentials are complete, just create it and set it to YES.

Check my answer to another question to see how I usually do this.

甜妞爱困 2024-10-03 05:16:09

在 Swift 3

let Defaults = UserDefaults.standard()()
let exists = Defaults.bool(forKey: "isLoggedIn")

if !exists {
   displayLoginScreen()            
} else {
   print("value exists..do something")
   displayMainScreen()       
}     

,我们也可以使用 object(forKey:) 然后将其转换为 bool

if let exists = Defaults.object(forKey: "isLoggedIn"), let isLoggedIn = exists.boolValue where isLoggedIn == true {
  displayMainScreen()
} else {
  displayLoginScreen() 
}

in Swift 3

let Defaults = UserDefaults.standard()()
let exists = Defaults.bool(forKey: "isLoggedIn")

if !exists {
   displayLoginScreen()            
} else {
   print("value exists..do something")
   displayMainScreen()       
}     

alternatively we can use object(forKey:) then cast it to bool

if let exists = Defaults.object(forKey: "isLoggedIn"), let isLoggedIn = exists.boolValue where isLoggedIn == true {
  displayMainScreen()
} else {
  displayLoginScreen() 
}
江湖彼岸 2024-10-03 05:16:09

Swift 2.3

存储值

    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "logged_in") 

用于获取值

  if NSUserDefaults.standardUserDefaults().boolForKey("logged_in") == true {
      dashboardScreen()
  }else {
      loginScreen()
  }

Swift 3.0

存储值

  UserDefaults.standard().setBool(true, forKey: "logged_in")

以检索值

  UserDefaults.standard().bool(forKey: "logged_in"){
      dashboardScreen()
  }else {
      loginScreen()
  }

Swift 2.3

To store values

    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "logged_in") 

For fetching values

  if NSUserDefaults.standardUserDefaults().boolForKey("logged_in") == true {
      dashboardScreen()
  }else {
      loginScreen()
  }

Swift 3.0

To store values

  UserDefaults.standard().setBool(true, forKey: "logged_in")

to retrieve values

  UserDefaults.standard().bool(forKey: "logged_in"){
      dashboardScreen()
  }else {
      loginScreen()
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文