在 dealloc 中保存对象状态不起作用

发布于 2024-11-01 22:08:29 字数 619 浏览 1 评论 0原文

我刚才注意到,当我在 dealloc 方法中保存对象状态(@public floats 转换为 NSStrings)时,使用了

+(void)savePreferences:(NSString*)key :(NSString*)value{
    NSMutableString* mutableString=[[NSMutableString alloc]initWithString:value];
    CFPreferencesSetAppValue((CFStringRef)key, mutableString, kCFPreferencesCurrentApplication);    // Set up the preference.
    CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);// Write out the preference data.
    [mutableString release];
}

错误的值保存!?如果我在发布之前保存这些值,则会保存正确的值。请注意,我在结束时小心地调用了[super dealloc];。这是为什么呢?

I noticed just now that when I save object state (@public floats converted to NSStrings) in my dealloc method, using

+(void)savePreferences:(NSString*)key :(NSString*)value{
    NSMutableString* mutableString=[[NSMutableString alloc]initWithString:value];
    CFPreferencesSetAppValue((CFStringRef)key, mutableString, kCFPreferencesCurrentApplication);    // Set up the preference.
    CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);// Write out the preference data.
    [mutableString release];
}

the wrong values are saved!? If I instead save the values just before releasing, the correct values are saved. Note that I am careful to call [super dealloc]; at the end. Why is this?

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

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

发布评论

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

评论(1

俯瞰星空 2024-11-08 22:08:29

该代码有几个问题;

  • 在 -dealloc 中保存状态已经太晚了。当调用 -dealloc 时,对象图正在被拆除。

  • 在应用程序终止时,系统不会浪费周期来拆除您的应用程序。它只会通知它即将终止,然后终止它;如果您依赖于调用 -dealloc,那么这种情况可能永远不会发生。

  • 这个方法名称不太好。尝试类似 savePreferencesValue:forKey: 的方法。然而,它可能被多次调用的暗示将导致显着的低效率(因为它会一遍又一遍地写入首选项 plist)。

  • 传入值的可变字符串副本会浪费周期和内存;不需要它

  • 除非您需要 CFPreferences*() 的扩展功能,否则您应该坚持使用 NSUserDefaults;它将导致更少的代码和更少的脆弱性。

Several issues with that code;

  • saving state in -dealloc is way too late. By the time -dealloc is called, the object graph is in the midst of being torn down.

  • on app termination, the system will not waste cycles tearing down your application. It'll just inform it that it is about to be terminated and then terminate it; if you are relying on -dealloc to be called, that might likely never happen.

  • that method name isn't very good. Try something like savePreferencesValue:forKey:. However, the implication that it may be called many times would lead to a significant ineffeciency (in that it'd write the preferences plist over and over).

  • the mutable string copy of the incoming value is a waste of cycles and memory; no need for it

  • unless you need the extended features of CFPreferences*() you should just stick with NSUserDefaults; it will lead to less code and less fragility.

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