Using the analyzer in XCode 4, I'm getting warnings of potential memory leaks due to setting a property like this:
self.newDog.dogName = self.dogNameTextField.text;
The specific warning is:
Property returns an Objective-C object with a +1 retain count (owning reference).
Object allocated on line 513 is not referenced later in this execution path and has a retain count of +1 (object leaked)
If I don't set the property using self, the warning goes a开发者_如何学Pythonway... but I'm not sure if that won't cause other issues since everything I've read basically says to always use self when setting/getting properties:
newDog.dogName = self.dogNameTextField.text;
Am I doing something else wrong here? Here's some stripped down code from the view controller where the warnings occur:
@interface AddDogViewController : UITableViewController {
Dog *newDog;
}
@property (nonatomic, retain) Dog *newDog;
@implementation AddDogViewController
@synthesize newDog;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// some other code
self.newDog.dogName = self.dogNameTextField.text;
// some other code
}
- (void)dealloc {
[newDog release];
[super dealloc];
}
@end
According to the memory management rules, a method that begins with new
returns a +1 retain count (just like alloc
and copy
). Your accessor newDog
has such a name.
You should rename your property to something that does not start with new
. Note that you're not actually leaking anything here. You're just confusing the analyzer because you're violating the naming rules.
This is because when you access your ivar
doing self.myIvar
, you are using the setter
method that was synthesized
to do so, and therefore if it was declared as retain
, it will send it an additionaly retain
msg.
This will not happen if you access the private variable directly, i.e. without using the setter which is without using self.myIvar
.
精彩评论