Reputation: 7283
Let's say I have an instance variable NSDate *date; and I do (for example in viewDidLoad):
date = [NSDate dateWithTimeIntervalSinceNow:0];
or
self.date = [NSDate dateWithTimeIntervalSinceNow:0];
Is there a difference between these two? And if there is which one is correct and possibly why :)
Thanx for answers Ladislav
Upvotes: 1
Views: 440
Reputation: 6402
If you use date = [NSDate dateWithTimeIntervalSinceNow:0]; here date is auto released object.
But if you use self.date and its property is retained,it is not a auto released object,we should explicitly release date
Upvotes: 1
Reputation: 92335
Yes, there is a difference. The first just assigns the value to the variable, while the other is assigning to a property and is thus the same as writing:
[self setDate:[NSDate dateWithTimeIntervalSinceNow:0]];
For example, if you've defined your property as @property(retain) NSDate *date;
the default implementation (through @synthesize date
) will release the old value and retain the new value. You could also provide a custom setDate:
implementation and do some actions when the date gets assigned. All of this doesn't happen if you just assign the value to the variable.
Upvotes: 4
Reputation: 1871
Yes. self.date calls the setter of the property called date and if you have given something like retain in the property specification or if you have provided your own accessors they will be called.
It is always good idea to use self.date than date in most cases unless you are absolutely sure. Also note that present compiler allows you to just decale a property and synthesize without using your own variable declaration. It is preferred over explicit variable declaration. If you use that construct, you will get compiler errors whenever you use the variable directly without using the accessor, which is a nice to have advantage.
Upvotes: 4
Reputation: 1439
By declaring self.date = some value; you are actually doing the following things
if(date)[date release]; date = [somevalue retain];
Upvotes: 1