简体   繁体   中英

iOS: using self causing a memory leak?

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:

  1. Property returns an Objective-C object with a +1 retain count (owning reference).

  2. 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 away... 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, ie without using the setter which is without using self.myIvar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM