Re: Setting pointer to nil
Re: Setting pointer to nil
- Subject: Re: Setting pointer to nil
- From: Shawn Erickson <email@hidden>
- Date: Tue, 20 Dec 2005 16:50:02 -0800
On Dec 20, 2005, at 3:11 PM, John Stiles wrote:
On Dec 20, 2005, at 3:01 PM, Shaun Wexler wrote:
On Dec 20, 2005, at 2:50 PM, Ricky Sharp wrote:
- (void)setManagedObjectContext:(id)newManagedObjectContext
{
[newManagedObjectContext retain];
[managedObjectContext release];
managedObjectContext = newManagedObjectContext;
}
FWIW, it's usually better & safer to write setters like this:
- (void)setManagedObjectContext:(id)newManagedObjectContext
{
id oldManagedObjectContext = managedObjectContext;
managedObjectContext = [newManagedObjectContext retain];
[oldManagedObjectContext release];
}
Out of curiosity, why? I see that this fixes a race condition, in
case you're writing multi-threaded code, but is there more to it
than that?
Well either are not really "safe" in a multi-threaded scenario so I
don't see a good reason to do it in a way other then what you are
doing. I could be missing some nuance....
id oldManagedObjectContext = managedObjectContext;
managedObjectContext = [newManagedObjectContext retain];
[oldManagedObjectContext release];
For example if thread one gets preempted after "id
oldManagedObjectContext = managedObjectContext;" and thread two gets
past "managedObjectContext = [newManagedObjectContext retain];"
before thread one comes around again then you have an over release
situation as well as a leak from a now lost reference.
Personally I use an if form (at least before bindings came around
since I would sometimes stick in the if block notification, defaults
updates, etc.). Again this isn't thread safe.
- (void)setManagedObjectContext:(id)newManagedObjectContext
{
if (managedObjectContext != newManagedObjectContext) {
[managedObjectContext release];
managedObjectContext = [newManagedObjectContext retain];
}
}
-Shawn
_______________________________________________
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