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.
The problem is that you wrote this:
startTime = blah blah blah;
You're setting the instance variable startTime
directly. If you do this instead:
self.startTime = blah blah blah;
then the compiler will turn it into this:
[self setStartTime:blah blah blah];
and the automatically-generated setter method will do the retain for you.
If you do this:
@synthesize startTime = _startTime;
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.