开发者

Is there a difference using self.variable = 'some value' to just variable = 'some value' for instance variables

Let's say I have an instance variable NSDate *date; and I do (for exam开发者_StackOverflowple 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


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.


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.


By declaring self.date = some value; you are actually doing the following things

if(date)[date release]; date = [somevalue retain];


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜