Still curious about memory management in Objective C
In a class derived from UIViewController there is a message implementation that is accessing derived property view
like this:
- (void) doSomethingOnView
{
MyView *v = (MyView *) [self view];
[v doOnView:YES];
[v release];
}
According to quick documenta开发者_如何学编程tion on property view of UIView it is a nonatomic read-write property in retain mode. My books here (e.g. "Beginning iPhone 4 Development" by Mark, Nutting, LaMarche) are reading that on reading properties in retain mode a release on obtained reference is required.
But my analyzer complains the [v release]
with "Incorrect decrement of the reference count of an object that is not owned at this point by the caller". Where is my fault?
In your first line, MyView *v
is just a pointer that is being set to point to a property already owned by your UIViewControllwer
. You UIViewController
has it through inheritence. It is declared elsewhere, not by you, therefore it is not alloc
ed by you.
When you set a pointer to point to an object which you never explicitly alloc
ed or retain
ed, you don't need to release
it, because you never increased its reference count. Read more here if you are curious.
So the point is, don't call [v release];
.
Consider the following code:
self.view = anotherView;
Then if view
is a property which is declared as retain
, anotherView
will be implicitly retained.
This works when you are assigning a variable.
In your code:
- You are not using properties (i.e. the dot notation)
- You are not assigning any variable
- You try to release something you did not allocate yourself with alloc for instance
Try reading the Declared Properties and Memory management guide sections of Apple's Objective-C documentation again if that is not clear.
You didn't alloc
the view, so you do not need to release it.
Where in the book are you reading that a release is needed in this case?
I think you misinterpreted what the book says. if you provide a quote we can explain it to you further.
In this case, you don't need to release cause there were no alloc
or retain
sent to v.
精彩评论