iPhone 设置应用程序保留数据

发布于 2024-08-19 11:40:35 字数 601 浏览 7 评论 0原文

在我的应用程序中,我使用 NSUserDefaults 对象在内置设置应用程序中存储用户名、密码和服务器 URL。如果没有保存数据,则会向用户显示登录界面,成功登录后将保存用户名和密码。然后在我的应用程序中,我有一个显示此信息的视图,但文本丢失,就好像数据尚未保存到“设置”中一样。这是代码:

...
NSUserDefaults* appSettings = [NSUserDefaults standardUserDefaults];
[appSettings setObject:username forKey:USERNAME];
[appSettings setObject:password forKey:PASSWORD];

if ( [appSettings synchronize] ) {

   // display an alert with a positive message
} else {
   // display an alert with a negative message

}

因此,登录后会显示积极的消息,但是当我再次获取数据时,那里什么也没有,除非我重新启动应用程序。

我需要做什么才能立即保存数据,或者至少在另一个视图控制器需要读取设置之前保存数据?

In my app I'm using an NSUserDefaults object to store the username, password and server URL in the built-in Settings app. If there is no data saved, the user is presented a login interface and upon succesful login the username and password are saved. Then in my app I have a view which displays this information, but the text is missing as if the data hasn't been saved to the Settings yet. Here's the code:

...
NSUserDefaults* appSettings = [NSUserDefaults standardUserDefaults];
[appSettings setObject:username forKey:USERNAME];
[appSettings setObject:password forKey:PASSWORD];

if ( [appSettings synchronize] ) {

   // display an alert with a positive message
} else {
   // display an alert with a negative message

}

So, after logging in the positive message is displayed, but when I fetch the data again there is nothing there, unless I restart the app.

What do I need to do to save the data immediatly, or at least before another view controller needs to read the settings?

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

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

发布评论

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

评论(1

烟花易冷人易散 2024-08-26 11:40:35

NSUserDefaults 对象将其数据存储在内存中,并且是一个全局对象(无论如何对于您的应用程序而言)。因此,您存储在其中的任何内容都应该可供随后尝试访问它的任何内容立即使用。您不需要在这里调用同步。如果您没有收到数据,则应该检查调用的顺序,以确保它们在您认为的时间被调用。

The NSUserDefaults object stores its data in memory, and is a global object (to your application, anyway). Thus, anything you store in there should be immediately available to anything that tries to access it afterwards. You don't need to call synchronize here. If you're not getting your data, you should check the order of your calls to make sure they're being called when you think they are.

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