To Retain or Not To Retain?

Ran into an interesting thing doing iPhone development yesterday.

I needed to pause an NSTimer object (which, of course, you can’t). So to work around this I was storing the start time of the timer in a class level NSDate object using the following.

In the header file:

NSDate *startTime;

and in the class file:

startTime = [NSDate date];

I did under the assumption that using the [NSDate date] static method would behave similar to the timer method I was using to start the timer. However when I would try to access the startTime object later it was deemed out of scope by the debugger.

I changed my line of code to look like this instead:

startTime = [[NSDate date] retain];

Basically I’m now explicitly retaining the value of startTime (which also means I have to release it later). What I don’t like is the inconsistency with the static method used to create a timer. I don’t need to explicitly retain the NSTimer object so why do I need to explicitly retain the NSDate object?


About Ruprect
iOS, Android and web developer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: