Re: Newbie: Object life within a method scope
Re: Newbie: Object life within a method scope
- Subject: Re: Newbie: Object life within a method scope
- From: "Martin" <email@hidden>
- Date: Wed, 23 Feb 2005 19:57:03 -0800
On February 23 2005, Joseph Feld <email@hidden> wrote:
>on 2/23/05 2:37 AM, Kevin Viggers at email@hidden wrote:
>
>> It would seem that your Java conditioning is steering you towards the
>> idea that objects are reclaimed by a separate thread (akin to the GC
>> thread in Java) and that objects could potentially be pulled out from
>> under your code, but this is typically not the case. It is only when an
>> object is shared between threads that this becomes a true concern.
>
>I think you hit the nail on the head, Kevin. I was just assuming without
>thinking about it that the actual object cleanup was happening in another
>thread once my objects signaled their readiness to be cleaned.
>Java-thinking, I know :-)
There is one case where objects can be pulled out from under your methods. It occurs when the object you pass into a method is somehow indirectly released by your own code. Consider the following unlikely scenario:
@interface XXWidget : NSObject {
NSMutableArray* _els;
}
- (void) processFirstElement ;
@end
@implementation XXWidget
- (void) processFirstElement
{
id firstObj = [_els objectAtIndex:0];
[self processFirstElement:firstObj inArray:_els];
}
- (void) processFirstElement:(id)firstObj inArray:(NSMutableArray*)array
{
// Replace the first element with something other than "firstObj". If
// "firstObj" is only retained by "array" then this will deallocate it.
[array replaceObjectAtIndex:0 withObject:[NSNull null]];
// Now do something with the first element, but it is already gone.
NSLog( @"%@", firstObj );
}
@end
In the cases where this has bitten me in the past the method accessing the deallocated object would have no idea that it might need to retain the object because the deallocated occurred several frames deeper in the call stack. Not that this has changes the way I code-- I definitely don't go retaining all parameters. Just something to be aware of.
~Martin
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden