Re: object ownership question
Re: object ownership question
- Subject: Re: object ownership question
- From: Peter Ammon <email@hidden>
- Date: Mon, 02 Jul 2001 09:35:10 -0700
on 7/2/01 2:53 AM, Candide Kemmler at email@hidden wrote:
>
Hi !
>
>
I'm just not used to be concerned about object ownership. Until
>
yesterday I didn't even know what a pointer was...
>
>
Now, my application crashes for a problem I think is related to object
>
ownership:
>
>
I have a button that gets data from a URL:
>
>
id url = [[NSURL alloc]
>
initWithString:@"http://localhost:8080/mapping/servlet/service"];
>
id handle = [ url URLHandleUsingCache:false ];
>
NSData *data = [ handle resourceData ];
>
So the NSData object that data points to is returned with a retain count of
1 and is autoreleased once, meaning that after your code is done and control
is returned to the main event loop, it will be released. Then it would have
a retain count of zero, so it would be deallocated; in other words, if you
want to keep this NSData around after your code returns, you have to retain
it.
>
[ mapView setData:data ];
>
>
in MapView, here's the setData method:
>
>
- ( void ) setData: ( NSData * ) data
>
{
>
// char *buffer;
>
// char **bufferHandle;
>
>
myData = data;
>
>
// buffer = ( char * ) [ myData bytes ];
>
// bufferHandle = &buffer;
>
// buffer += 4;
>
// NSLog ( @"\nthe float value is %f", readFloat ( bufferHandle ) );
>
>
}
>
>
the myData instance variable in MapView is defined like so:
>
>
@interface MapView : NSView
>
{
>
NSData *myData;
>
}
>
- (void)drawRect:(NSRect)frame;
>
- ( void ) setData: ( NSData * ) data;
>
@end
>
>
>
>
The commented code in setData works, which means that the myData object
>
contains valid data.
>
>
However, when I try to execute the same code in drawRect, my application
>
crashes.
>
>
Who could shed some light for me on this basic topic ?
What's happening is that after your setData method is called and before the
drawRect method is called, control is returned to the run loop, so the
autorelease kicks in and your NSData is released. Since it has a retain
count of 1, the autorelease drops it down to 0, and the object is
deallocated.
The right thing to do is to change your setData method to be:
myData = [data copy];
This will make an NSData with the same contents as your data variable and a
retain count of 1, but it won't be autoreleased. This means that it won't
be deallocated on the next pass through the run loop.
Hope this helps.
-Peter