RE: [OT] Retain count riddle
RE: [OT] Retain count riddle
- Subject: RE: [OT] Retain count riddle
- From: "Jonathan E. Jackel" <email@hidden>
- Date: Tue, 30 Mar 2004 15:31:23 -0500
Not much of a riddle.
>
So I had this bug the other day that I thought would make an interesting
>
riddle.
>
>
The code looked like this:
>
>
#define SAFE_SET(old, new) [new retain]; [old release]; old = new;
>
>
...
>
>
- (void) foo : (NSString*)path {
>
SAFE_SET(m_Path, [path lastPathComponent]);
>
}
>
>
Now the problem was any time I accessed m_Path my app would crash. This
>
isn't cocoa specific, I'm just dumb for using macros where I should have
>
been using a function. Can anyone guess what the problem is ?
The preprocessor will change your code to the following:
-(void)foo:(NSString *)path
{
[[path lastPathComponent] retain];
[m_Path release];
m_Path = [path lastPathComponent];
}
The first statement has no beneficial effect. You've retained a string that
is not assigned to a variable and there's no way of accessing that
particular string object ever again. So it leaks.
Then you release m_Path, so the original value is gone.
Then you set m_Path to [path lastPathComponent]. This is NOT the same
NSString instance that you retained back on the first line. It is a newly
generated, autoreleased string. It is released when the autorelease pool is
released. That's why you crash.
This should sorta work:
#define SAFE_SET_PATH(old, new) NSString *temp = [[new lastPathComponent]
retain]; [old release]; old = temp;
But you risk namespace collisions with temp.
Is it really so difficult to write proper accessors the long way, or use a
tool like Accessorizer? The benefit is that you can instantly debug
problems like this. Do you save enough effort using macros for that
practice to pay off?
Jonathan
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.