I a few simple questions to make sure I am using properties right in my application. I read a lot online but it is still unclear. Thanks a lot for any help or suggestions.
(1) I am not quite sure that the statement does, and why is it needed.
@synthesize personName = _personName;
Why do you need the _personName variable? What is the benefit of doing that as opposed to just creating a property and synthesizing that variable personName.
@property (nonatomic, retain) NSString *personName;
(2) In my application should I be accessing the property variable self.personName or use the _personName variable. I believe the self.personName is correct by then again why is the _personName even there?
(3) Also I am a little confused to which variable I should release in dealloc() and which variable should I set to nil in viewDidLoad(). I also do not know if any 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
That statement creates the accessor methods for the
personNameproperty. You’ve specified that the accessors should use an instance variable named_personName. If you just had@synthesize personName;, the accessors would usepersonNameas the instance variable instead.You should usually use the accessor methods, as in
self.personNameorsomePerson.personNameorsomePerson.personName = @"Joe";. If you don’t care what the name of the ivar that backs up thepersonNameproperty, you don’t need to specify it.Use the accessors in
-viewDidLoad, as in:self.personName = nil;. Same for-didReceiveMemoryWarning:. Whether to use the ivar or property in-deallocis debatable, and to some degree a matter of taste. The main concern with using the property accessors in-deallocis that it can cause problems if your class is subclassed and the accessors are overridden. Often, you don’t need to worry about that because you know that your class won’t be subclassed.Setting an ivar to nil after releasing is also debatable. Many people feel that it’s good style to do so, others feel like it’s a waste of time. Use your best judgement. It’s certainly not necessary, but rather something that some feel is a matter of good housekeeping.