NSUserDefaults standardUserDefaults setObject 在 defaultsChanged 中崩溃

发布于 2024-12-20 01:40:01 字数 498 浏览 4 评论 0原文

我遇到了一些我不明白的事情。我已在手机的设置菜单中为应用程序设置了语言选择。 我的 AppDelegate 中有委托方法

- (void)defaultsChanged:(NSNotification *)notif 

。我读取了所选语言的新参数,并尝试更改语言,

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];

不幸的是,这一行总是给我一个 EXC_BAD_ACCESS 错误。我不明白为什么。

我尝试了 StackOverflow 上给出的不同方法来在运行时更改本地化,但它们仅适用于应用程序中的文本。我还有本地化的图像,它们仅在 NSUserDefaults 中更改语言时更新。

我在这里需要一些建议。

谢谢 !

I ran into something I don't understand. I have set a language selection for the application in the settings menu of the phone. I have the delegate method

- (void)defaultsChanged:(NSNotification *)notif 

in my AppDelegate. I read the new parameter of the selected language and try to change the language with

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];

Unfortunatly this line always gives me a EXC_BAD_ACCESS error. I don't understand why.

I tried different ways given on StackOverflow to change Localization at runtime but they only work for texts in the application. I also have images that are localized and they only updates when the language is changed in the NSUserDefaults.

I need some advices here.

Thank you !

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

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

发布评论

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

评论(1

拥抱影子 2024-12-27 01:40:01

在我看来,在 defaultsChanged 处理程序中更改 NSUserDefaults 确实不是一个好主意。根据您自己的评论,它会导致递归。

如果您确实需要更改 defaultsChanged 中的 NSUserDefaults,解决方法是添加一个布尔标志,表示您正在进行更改,以便您知道在响应时不要执行任何操作你自己的改变。

也许您的状态需要与 NSUserDefaults 不同的存储方法,例如 plist。我知道 NSUserDefaults 使用起来确实很方便,这是人们使用(有时误用)它来处理实际上不是用户偏好的各种状态的主要原因,但由于它的所有花哨功能,它可能会导致问题附带,例如对 NSUserDefaultsDidChangeNotification 观察者的支持。

It does seems to me that making changes to NSUserDefaults inside the defaultsChanged handler is not a good idea. As per your own comment it causes recursion.

If you do need to change the NSUserDefaults inside your defaultsChanged, a workaround would be to add a boolean flag that says you're making changes so that you know not to do anything when you are called in response to your own changes.

Perhaps you need a different storage method than NSUserDefaults for your state, such as a plist. I know that NSUserDefaults is really convenient to use, and that is the main reason people use (and sometimes misuse) it for all sorts of state that isn't actually user preferences, but it can cause problems due to all the bells and whistles it comes with, such as the support for NSUserDefaultsDidChangeNotification observers.

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