在 dealloc 中保存对象状态不起作用
我刚才注意到,当我在 dealloc 方法中保存对象状态(@public float
s 转换为 NSString
s)时,使用了
+(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 float
s converted to NSString
s) 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码有几个问题;
在 -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.