简体   繁体   中英

Objective-C 2.0; Assigning a Property; Leaking Memory?

I'm still learning about Objective-C memory management. I'm trying to implement several simple classes in an example program that I'm building.

As an example, say I have the following class definition:

 #import <UIKit/UIKit.h>

 @interface customViewController : UIViewController 
 {
    customObject *myCustomObject;
 }

 @property (retain) customObject *myCustomObject;

 - (void)replaceCustomObject:(customObject *)newObject;

 @end

For the property, I use the standard synthesize keyword...

@synthesize myCustomObject;

Then please assume that in the instance of customViewController the myCustomObject is already set with a valid value and is in use. Then the method replaceCustomObject is defined as:

 - (void)replaceCustomObject:(customObject *)newObject
 {
     //Does this cause a memory leak because I just assign over
     //the existing property? 
     self.myCustomObject = newObject;
 }

As the comment asks, does this leak memory? Or is this the valid way to replace a previous object with a new object?

Thank you,
Frank

As others have mentioned, your code is perfectly valid and won't leak memory when assigning to the property.

If you have forgotten to implement a proper dealloc method, the last object assigned will be leaked when your customViewController is destroyed. A proper dealloc implementation would look like so:

- (void)dealloc
{
    self.myCustomObject = nil;
    [super dealloc];
}

That's perfectly valid, and does not leak memory. The synthesized accessors manage retain counts correctly.

(As an aside, you don't need that replaceCustomObject: method; since your property is readwrite by default, you have an auto-generated setCustomObject: method that clients of your class can use, and which follows the normal Cocoa naming conventions.)

According to this , if you use (retain) in your declaration, the synthesized method will release the old value first, then retain the new one:

if (property != newValue) {
    [property release];
    property = [newValue retain];
}

the property accessor syntax

self.x = y;

has the same effect as calling the setter method explicitly:

[self setX:y];

The accessor method will do whatever it has been written to do. In your case, for a @property(retain) property that has been @synthesized, the accessor will release the old object and retain the new one.

So, calling the setter, whether explicitly or through the '.' syntax, will do the right thing - including the right memory management.

So in short: no, this will not leak memory.

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