NSUserDefaults,仅在第一次加载时执行某些操作
我试图在应用程序第一次启动时显示警报。如果他们稍后进入设置页面并希望再次看到它,我还想显示此警报。我想我可以在 NSUserDefaults 中设置一个布尔值。我不太确定如何做到这一点(假设这种方法是正确的)。我认为在 applicationDidFinishLaunching:options
中,我可以获取键 @"FirstTimeLaunched"
的值,在 applicationWillTerminate
中,我可以设置该对象该键为NO
。如果是这种情况,如何让 BOOL
第一次变为 YES
?
另外,我是否也需要在 didEnterBackground
模式下将其设置为 NO
?谢谢。
I'm trying to do show an alert the first time the app is launched. I'd also like to show this alert if they go into a settings page later on and want to see it again. I figured I could set a boolean in the NSUserDefaults
. I'm not quite sure how to do that though (assuming this approach is right). I thought in applicationDidFinishLaunching:options
, I could get the value for key @"FirstTimeLaunched"
, and in applicationWillTerminate
, I could set the object for that key to NO
. If this is the case, how do I get the BOOL
to be YES
for the first time?
Also, do I need to set it to NO
in didEnterBackground
mode as well? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
倒过来想想,不要期待
YES
,而是在应用程序实际启动时设置一个变量,并在用户在设置中这么说时将其删除。启动时:
当用户想再次看到它时,只需删除该密钥即可:
当访问不存在的密钥时,
NSUserDefaults
将返回nil
。Just think it backwards, instead of expecting a
YES
, set a variable when the app is actually launched, and remove it when the user says so in the settings.At launch:
And when the user wants to see it again, just remove the key:
When accessing a key that does not exists,
NSUserDefaults
will returnnil
.我会采取相反的方法,首先启动检查名为 appHasLaunchedPreviously 的密钥。
如果是,则绕过警报。
如果不是“是”,则显示警报并立即为下次做好准备。
I would take the opposite approach and first launch check for a key called appHasLaunchedPreviously.
If it's yes then bypass the alert.
If it's not YES then show the alert and immediately set it ready for next time.
第一次启动应用程序时,因此我认为您不需要将
BOOL
设置为NO
。如果应用程序被删除,UserDefaults
也会被删除。我们在App首次启动时设置它didFinishLaunchingWithOptions:
如果您在
applicationWillTerminate
中将Bool
设置为NO
,那么每次用户从托盘中杀死应用程序时,您都会在应用程序启动时显示警报。同样,这取决于您的业务需求。First time App is launched, so I don't think you will ever need to set that
BOOL
toNO
.UserDefaults
gets deleted if App is removed. and we set it when App is first launched applicationdidFinishLaunchingWithOptions:
If you set
Bool
toNO
inapplicationWillTerminate
, then everytime user kills app from tray you will show alert on app launched. Again it depends on your business requirements.