Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the differences between the usage of self.property and property [duplicate]

Possible Duplicate:
difference between accessing a property via “propertyname” versus “self.propertyname” in objective-c?

In my class, i am not sure whether to use self.property of property, such as

  dateFormatter = [[NSDateFormatter alloc] init];
  //or
  self.dateFormatter = [[NSDateFormatter alloc] init];

They both seem to work fine. Are there any differences between these two usage? I am confused.

like image 771
lu yuan Avatar asked Dec 01 '25 22:12

lu yuan


1 Answers

property is inface your methods getter and setter, when ever you call it via self.dateformator, it will call the property if you have synthesized the object and self generated getter and setter naming(setProperty and getProperty),

in your case, your first line is not the propery, you are accessing directly the iVar of your class while in 2nd line of your code you are using the property getter and setter methods,

now your question what is the difference,

the difference is that in iVar access(your first line), you will have to manually release the object and will have the retain count of 1 increased, and memory allocted will be accociated to it. while in self.property, a memory is allocated, but a new block will be assign to the variable as apple property management do this. but the retain count will be again the same.

so a block of memory will be lost.

Now i would like to tell some thing beneficial that is the good approach is to use properties for object, because if you have written retain in the property attributes in interface file, then your memory management will be at the compileres end, but remember to write release in dealloc method. and for code lines that you have writter here, like

self.someProperty = [[NSArray alloc] init];

use it as

NSArray* arr = [[NSArray alloc] init];
 self.someProperty = arr;
 [arr release];

now your retain count will be same as you want that of one, and don'd care of where to release this, it will auto release in dealloc method if you writtern it.

and for the one you write earlier, you will have to keep track that where you have to release the object

like image 144
Saad Avatar answered Dec 03 '25 13:12

Saad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!