IPhone Properties
I'll have a few simple questions to make sure I'm using properties right in my application. I have read a lot on the internet but it is still unclear. Thanks a lot for any help or suggestions.
(1) I'm not entirely sure what this statement is and why it is needed.
@synthesize personName = _personName;
Why do you need the _personName variable? What is the advantage of this rather than just creating a property and synthesizing that personName variable.
@property (nonatomic, retain) NSString *personName;
(2) My application should be able to access the self.personName property variable or use the _personName variable. I believe self.personName is correct by then why does _personName exist even there?
(3) Also I'm a little confused about which variable I should post in dealloc () and which variable I should set to nil in viewDidLoad (). I also don't know if changes should be made to the didReceiveMemoryWarning () method.
@interface ViewController : UIViewController
{
NSString *_personName;
}
@property (nonatomic, retain) NSString *personName;
@end
@implementation ViewController
@synthesize personName = _personName;
- (void)viewDidLoad
{
[super viewDidLoad];
self.personName = [[NSString alloc] initWithString:@"John Doe"];
NSLog(@"Name = %@", self.personName);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)dealloc
{
[super dealloc];
}
@end
source to share
@synthesize personName = _personName;
-
This statement creates accessor methods for the property
personName
. You indicated that accessors should use an instance variable named_personName
. If you just had@synthesize personName;
, you would usepersonName
accessors as an instance variable instead . -
Usually you should use accessor methods like in
self.personName
orsomePerson.personName
orsomePerson.personName = @"Joe";
. If you don't care what the name of the ivar that the property supportspersonName
, you don't need to specify it. -
Use the accessor to
-viewDidLoad
, as in:self.personName = nil;
. The same goes for-didReceiveMemoryWarning:
. Whether to use an ivar or a property in-dealloc
is controversial and somewhat a matter of taste. The main problem with using property accessors-dealloc
is that it can cause problems if your class is a subclass and the accessors are overridden. Often times you don't need to worry about this because you know your class will not be subclassed. -
Setting Ivar to zero upon release is also controversial. Many people think this is good style, others think it is a waste of time. Use your best judgment. This is certainly not necessary, but rather what some consider a good home.
source to share