Memory management, should the release be used in this case?
Given the following piece of code from within the method;
NSBezierPath * tempPath = [NSBezierPath bezierPathWithOvalInRect:pathRect];
[tempPath retain];
[path release];
[self setPath:tempPath];
Am I in charge of releasing tempPath
, or will it be done for me?
Setpath @synthesize
d is being set, so I might be able to leave as well [path release]
?
I know the best way to do this is simply:
[path appendBezierPathWithOvalInRect:pathRect];
But as a newbie to Objective C and Cocoa, I'm trying to figure out how things stack up.
--- ADDED CONTENT
The output [tempPath retain]
crashes on an object NSView
that uses paths.
Debugger output:
(gdb) po [0x145dc0 path] Program received signal EXC_BAD_ACCESS, Could not access
memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00000021 0x93c56688 in objc_msgSend ()
CONFESSION GUILT is my mistake. Hope someone else gets something helpful from my error. I used assign
instead retain
in the ad @property
. When committing the code, the code worked as expected.
THANKS FOR GUI HELP
source to share
If path
is an instance variable holding a method -setPath:
, then no, you absolutely shouldn't release it outside of your method -dealloc
. You don't need to manually save your object tempPath
as you are using an accessor to save that object. Your accessors, -setPath:
in this case, methods -init
, and -dealloc
should be the only method in which you would have to call -retain
and -release
your instance variables.
Your code works just as well, and with less chance of memory leaks:
NSBezierPath *tempPath = [NSBezierPath bezierPathWithOvalInRect:pathRect];
[self setPath:tempPath];
Since the method -bezierPathWithOvalInRect:
returns an auto-implemented object and your helper will save it, you don't need to do anything with it.
source to share
Let's look at it differently:
If you haven't used synthesized accessors, you write them yourself. In their simplest forms, they would look like this:
- (NSBezierPath *) path {
return path;
}
- (void)setPath:(NSBezierPath *)newPath {
if (path == newPath) {
// both objects have the same pointer so are the same.
return;
}
[path release];
path = [newPath retain];
}
You can see that the old path is freed and the new path is stored inside the setter, so you don't need to do this from your method, which can be written as
self.path = [NSBezierPath bezierPathWithOvalInRect:pathRect];
source to share