为什么我需要保留 NSDateFormatter dateFromString 的结果:
我有一个 NSDate*,我将其存储为带有保留关键字的属性:
@property (nonatomic, keep) NSDate* startTime;
我按如下方式使用它:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"h:mm a"];
startTime = (NSDate*)[[NSUserDefaults] standardUserDefaults] objectForKey:@"StartTimeKey"];
if (startTime == nil)
startTime = [[dateFormatter dateFromString:@"8:00 am"] retain];
为什么我需要保留结果dateFromString:
消息的结果,但我不需要保留 objectForKey:
的结果?
我刚刚升级到 XCode 4.2,现在使用 LLVM GCC 4.2 编译器。升级之前,代码在没有保留的情况下运行良好。现在它崩溃了(稍后在代码中,当我访问 startDate 属性时),没有保留消息。
I have an NSDate* that I'm storing as a property with the retain keyword:
@property (nonatomic, retain) NSDate* startTime;
I use it as follows:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"h:mm a"];
startTime = (NSDate*)[[NSUserDefaults] standardUserDefaults] objectForKey:@"StartTimeKey"];
if (startTime == nil)
startTime = [[dateFormatter dateFromString:@"8:00 am"] retain];
Why do I need to retain the result of the dateFromString:
message, but I don't need to retain the result of objectForKey:
?
I just upgraded to XCode 4.2 and I'm now using the LLVM GCC 4.2 compiler. Before the upgrade, the code worked fine without the retain. Now it crashes (later in the code when I access the startDate property) without the retain message.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案在内存管理编程指南第11页。
你拥有一个你创建的对象(也就是说你不需要保留它,它已经完成了)。您可以使用 alloc、new、copy 或 mutablecopy 创建对象。
在这种情况下,dateFormatter 为您提供了一个新对象,但是,由于您没有自己调用 alloc、new 或 copy,dateFormatter 将在新的 NSDate 对象上调用(通常是其工作方式)autorealease。
但是,如果您使用 setter 和 getter 设置属性,则不会出现此问题。
The answer is in the Memory Management Programming Guide on page 11.
You own an object you create (that is you do not need to retain it, it has been done ). You create an object with alloc, new, copy or mutablecopy.
In this case, the dateFormatter gives you a new object but, since you did not call alloc, new or copy yourself, dateFormatter will call (normally its how it works) autorealease on the new NSDAte object.
But, if you were setting your property using the setter and getter, you would no have this problem.
问题是您这样写:
您直接设置实例变量
startTime
。如果你这样做:那么编译器会将其转换为:
并且自动生成的 setter 方法将为你执行保留。
如果这样做:
那么实例变量将被命名为
_startTime
,这样更容易记住使用该属性,而不是直接分配给实例变量。The problem is that you wrote this:
You're setting the instance variable
startTime
directly. If you do this instead:then the compiler will turn it into this:
and the automatically-generated setter method will do the retain for you.
If you do this:
then the instance variable will be named
_startTime
, making it easier to remember to use the property instead of assigning to the instance variable directly.