Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate init question, related to memory management in Objective-C

I have an NSDate object created by

NSDate *date = [[NSDate alloc] init];

Later, I want to reset the date to the "now", so I thought that

[date init];

or

date = [date init];

might do the job, but they don't. Instead,

[date release];
date = [[NSDate alloc] init];

works. I'm a bit confused about this, since in the documentation for - (id) init, it says:

Returns an NSDate object initialized to the current date and time.

and since date is already allocated, shouldn't it just need an init message?

like image 790
Jesse Beder Avatar asked Dec 10 '22 19:12

Jesse Beder


1 Answers

Think of alloc and init as logically inseparable halves of a constructor. You can only call methods beginning with "init" once on a given object — once the object has been initialized, and it's an error to initialize it again. This is true for any Objective-C object, not just NSDate. However, NSDate objects are also immutable — once created, they can't change.

The reason the latter code works is because you're creating a new instance of NSDate, which is the correct thing to do. You can also use [NSDate date] to accomplish the same thing. Be aware that it returns an object that you don't (yet) own, so you'll need to retain it if you need to keep it around, and release it later.

Be aware that if you receive an object from someone, it has already been initialized. (If not, it's a programming error in the code that provided it, or is an extremely uncommon exception to the rule.)

like image 167
Quinn Taylor Avatar answered May 13 '23 15:05

Quinn Taylor