开发者

When to use self with instance variables assignments in iphone

开发者 https://www.devze.com 2023-01-12 23:08 出处:网络
I have some confusion about when to use the self keyword during ivars assignment, should I use it when I\'m trying to assign certain value to ivar or only when I\'m trying to access the ivar?

I have some confusion about when to use the self keyword during ivars assignment, should I use it when I'm trying to assign certain value to ivar or only when I'm trying to access the ivar?

Besides, if I do retainCount on an ivar after its assignment without using self, it prints a count of 1 assuming it was already alloc & init. But if I use self it gives me retain count of 2.

Example Code:

Titles = [[NSMutableDictionary alloc] init];

NSLog(@"Titles before assignment: %d", [Titles retainCount]); // print 1

Titles = anotherDictionary; NSLog(@"Titles after assignment: %d", [Titles retainCount]); // print 1

self.Titles = anotherDictionary; NSLog(@"Titles after assignment: %d", [Titles retainCount]); // print 2

Should not I use self during assignment or when should I use? Any help would be really very appreciated开发者_StackOverflow社区 as this situation is giving me a lots of doubts that my ivars are not being released the proper way.

Thanks, Mohsen

Edit: I have another related issue to my above question, should I use self to assign singleton classes properties?


When you use Titles = ... you are assigning to the variable directly. When you use self.Titles = ... you are actually using a dynamically generated setter method.

BTW, I think recommended practice is that properties start with a lower case.

Do some reading on properties and how they are accessed.


You don't use self to assign ivars nor to read them. You use it to read/write properties ie call methods/send messges.

So in your example:

Titles = anotherDictionary;

Assigned the ivar without calling the setter while

self.Titles = anotherDictionary;

Was actually

[self setTitles:anotherDictionary];

Which is usually automatically generated by @syntetize Titles. The code of the setter automatically retain objects when the @property has retain flag.

Recommended practice: Once you have the properties that take care of the memory management you should use them. Instead of retian/release objects manually.

Here is the apple's guide I was learning from.

Update:

Regarding the memory management and just check the apple's memory management programming guide It answers your question asked in comment. It shows by example how to use the memory management provided by properties.

0

精彩评论

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