Preventing leaks when using @property and @synthes

2019-06-08 17:29发布

问题:

What steps should we take -- what are the best practices -- to prevent leaks when using @property and @synthesize?

回答1:

Be aware of your standard things that give you back retained objects, methods with alloc, copy or new. When you invoke these along with your property you can inadvertently create a leak.

In your interface you have

@property (nonatomic, retain) NSArray *someArray;

And in your implementation you have

@synthesize someArray;

Then later on you use the the property

self.someArray = [[NSArray alloc] init];

your object now has a retain count of 2. one from using self.someArray = and one from the alloc. self.someArray = invokes your setter which is the same as - (void)setSomeArray:(NSArray)someArray; which is created for you with the synthesize. This is going to contain a retain because of the retain keyword you used in the @property declaration.

I tend to avoid this one of two ways.

either with using the autoreleased intializer

self.someArray = [NSArray array];

or

self.someArray = [[[NSArray alloc] init] autorelease];

or use a temp variable

NSArray tempArray = [[NSArray alloc] init];
self.someArray = tempArray;
[tempArray release];

all of these methods will leave you with your self.someArray object having a retain count of one which you can take care of in the dealloc.

- (void)dealloc {
[someArray release];
[super dealloc];
}


回答2:

One thing that has helped me a lot is to check your header file for property definitions with a retain type, and then make sure that there is a release for each of them in the -dealloc method.

For the various assignments to the properties during the lifetime of the object, the automatic synthesized setters should take care of it.