Why do I need to retain the result of NSDateFormatter dateFromString:

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.

Need Your Help

creating a delay on silverlight

silverlight timer delay dispatchertimer

I am making a turn based silverlight game(Cards game). and I want to delay between turns.

Call a function if userinteraction is nil for 3 seconds

iphone ios ios4 ios5

Guys i need to call a function in such a view that if there is no user interaction for three seconds the function should be called

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.