While creating a custom iOS table view cell, I created a new .xib file, dragged/dropped some UI elements in interface builder and my .h file looked like this…
#import <UIKit/UIKit.h>
@interface MasterTableViewCell : UITableViewCell
{
IBOutlet UILabel *cellLabel;
IBOutlet UIImage *cellImage;
}
@property (nonatomic, retain) IBOutlet UILabel *cellLabel;
@property (nonatomic, retain) IBOutlet UIImage *cellImage;
@end
On some blogs I saw that the instance variables were missing. When do I need to declare instance variables? Are both instance variables and @property declarations not needed for a particular UI object.
Also I am creating the app using automatic reference counting, so garbage collection needs aren’t there as well. What difference does that make in usage of instance variables & properties?
There is no garbage collection in iOS. iOS uses reference counting to track ownership of objects. Using ARC does not do away with reference counting, but the compiler takes care of releasing and retaining objects. When using ARC you are not allowed to send a retain, release, or autorelease message to an object, nor are you allowed to call [super dealloc] in a dealloc method. In your code above, since you are using ARC, the ‘retain’ attributes should be replaced by the ‘strong’ attribute.
When you use @property, and the corresponding @synthesize in your implementation, you do not need to create a backing instance variable – the compiler does that for you. @property along with @synthesize create your accessor methods (your getters and setters), and also enable you to use dot notation to refer to your objects’ properties. You may still write your own accessor methods if you choose.
The above code could be replaced by the following:
In your implementation file you would have:
or
In your code, to ensure that you are using your accessor methods, use ‘self’ to refer to your properties:
or
I hope this helps clarify things a little.