开发者

self function is used

wh开发者_JAVA技巧y self is used ....what is the meaning for self.something = manything;


The main difference is calling without the self will access the variable directly and calling via self will call the set/get method. What is the différence ?

Because you need to be carefull about memory in Objective-C and when you do something = manything; manything is attached to something and the object previously attached to something is lost.

And the good thing to do is to use the set method which take care about releasing the old object before setting the new one. You can just remember that to set something it's always better to use the self.something.


An example just to be clear:

1) If you do (assume that myArray is a property): BAD CASE

NSArray *tmpArray = [NSArray arrayWithObjects:@"obj1", @"obj2", nil];
myArray = tmpArray;

The first line create an autoreleased array, then we assign this array to myArray. If something was in myArray, its not released and the new array is not retain. This will lead to memory leaks and a crash when we will try to access myArray after because the autoreleased array will be released.

2) If you do this: GOOD CASE

NSArray *tmpArray = [NSArray arrayWithObjects:@"obj1", @"obj2", nil];
self.myArray = tmpArray; //Equivalent to [self setMyArray:tmpArray];

We are calling the accessor method here and this method will take care of releasinf the old object if needed ( no memomry leaks) and will retain the new assign object if it's also needed (the array is now retained by our property and can be accessed in the furure).

=> To resume, it's all about memory management.


Whenever you set property of a variable & if you want to access the property in the same class we generally use

self.(ObjectName)    //for accessing getter & setter method.

One additional benefit is if you want to use any object in other class too we use to synthesize that object & creating the object of that class we can access the member variables of that class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜