Objective-C 2.0; Property assignment; Memory leak?

I am still learning Objective-C memory management. I am trying to implement some simple classes in an example program that I am creating.

As an example, let's 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 synhesize keyword ...

@synthesize myCustomObject;

Then, please assume that in the customViewController instance myCustomObject is already set to a valid value and is used. Then the replaceCustomObject method 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 a comment observes, does this memory leak? Or is this a valid way to replace the previous object with a new object?

Thanks
Frank

+3
4

. .

( , replaceCustomObject:, readwrite, setCustomObject: , Cocoa .)

+2

, .

dealloc, , , , customViewController . dealloc :

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

this, () , , :

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

resource access syntax

self.x = y;

has the same effect as calling the setter method:

[self setX:y];

The access method will do everything he wrote. In your case, for the @property property (persistence) that was @synthesized, the accessor will free the old object and save the new one.

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

In short: no, this is not a memory leak.

+1
source

Source: https://habr.com/ru/post/1707567/


All Articles