What is the difference between the following two approaches for the self syntax to access the object properties:-
Approach 1:-
self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
Approach 2:-
effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.
I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.
Please enlighten me.
Thank you All
In the first syntax:
you are accessing both ivars through their accessor methods (usually,
effortViewto get,setEffortViewto set).In the second syntax:
you are accessing the
effortViewivar directly (pointer assignment), while you are accessingeffortTableViewthrough its property accessor.The difference is that using an accessor you obtain additional behavior. Like, with the standard
setaccessors generated by the@synthesizekeyword for aretainproperty:you get automatic retain count management (i.e., retain count will be automatically incremented on the assigned object; if the ivar had already a value, the object pointed to will have its retain count decreased). What this implies is that in your first example, you are causing 2 memory leaks. Indeed, (if the properties are declared as
retainproperty) assigning to them will increase their retain count; but[[alloc] init]already gives back an object with a retain count of 1, so you don’t need to increment it once more. Correct would be:Overall, properties make much easier to deal with retain count management and are the suggested way to go with it, but you have to be aware of their “retain count” semantics and account for that.
I would suggest this article as an interesting reading.