So here is my code:
-(void)setMovie:(NSURL *)movieLocal {
movie = movieLocal;
[self.movie retain];
...
}
And i get this error:
Potential leak开发者_如何学Python of an object allocated on line 43
Line 43 is [self.movie retain];
. Am i doing something wrong, and how can i get rid of this error?
There are a couple issues here:
- The old value for
movie
is never released - 'movie' and 'movieLocal' might point to the exact same object. If that is the case, you will call retain on movie/movieLocal without a subsequent balanced release call.
You might want to use the following:
-(void)setMovie:(NSURL *)movieLocal {
if (movie == movieLocal) {
return;
}
[movie release];
movie = [movieLocal retain];
//...
}
Here's the proper setter:
-(void)setMovie:(NSURL *)movieLocal {
if (movie != movieLocal) {
[movie release];
movie = movieLocal;
[movie retain];
}
}
However, if you declared your property (in .h file):
@propert (nonatomic, retain) NSURL *movie;
and synthesized it in .m file, by @synthesize movie;
, than there is no need to explicitly override the setter - the code above will be generated automatically for you. So whenever you want to set your movie
you'll just call self.movie = newMovie;
which will be equivalent to calling [self setMovie:newMovie];
.
For more info read a section "Declared Properties" in Learning Objective-C guide.
EDIT: to explain what was wrong with your setter.
-(void)setMovie:(NSURL *)movieLocal {
movie = movieLocal; // first line
[self.movie retain]; // second line
...
}
In 1st line you are assigning movie
to point to movieLocal
, but you don't release old NSURL
object that movie
was pointing to before assignment. This was way, your causing a memory leak - you abandon memory, so it can never be relinquished back by your app. In general, abandoning memory is an easy way to get you application terminated by iOS, when objects are big and often leaked.
In 2nd line you are calling you setMovie
setter again as self.movie =
syntax causes the runtime to call a setter for movie
property. This time it'll cause an infinite loop.
I hope my wording was clear for you and my answer helpful.
精彩评论