SundayMonday
SundayMonday

Reputation: 19727

Why doesn't the Objective-c runtime set dealloc'd object instances to nil?

Sometimes I set objects to nil after releasing them to avoid crashes due to unexpected messages sent to dealloc'd objects.

Why doesn't the Objective-c runtime do this automatically when an object is finally dealloc'd?

Upvotes: 4

Views: 185

Answers (4)

Barry Wark
Barry Wark

Reputation: 107754

What you are describing is called a zeroing weak reference. This feature is available in OS X 10.7's Automatic Reference Counting (ARC) runtime. Prior to 10.7, you can use Mike Ash's zeroing weak reference implementation.

Without explicit runtime support (and some small but unavoidable overhead), standard C-style pointers (id in Objective-C is a pointer to a structure) are just a memory address (an integer) and not tracked by the runtime. There's nothing stopping you from making copies of this value elsewhere in memory or from storing the value in an integer of the appropriate size and casting to an id later on (of course if you do any of this, you kill a baby seal). Thus, when an object is dealloc'd there's no way to know where (or how many) references there are to that object.

Upvotes: 3

Jaffa
Jaffa

Reputation: 12700

In objective-C, the objects are always accessed as pointer. Setting an object to nil simply change the pointer value, not the object value.

In your method, you have only access to the object's value, not to the pointer pointing to it!

As @David Dunham says, you can have more than one pointer to an object, so how would the compiler knows?

And more than that, to make things easier, imagine the following code :

int a;
int* aPtr = &a;

If you change a value, you can access the changed value via *aPtr right? But you can change a value as long as you want, it won't change aPtr value, as it is not the same variable!

Thus, even if you only have one pointer to your object, if you modify the object's value, you pointer will still point to the same address value!

Upvotes: 3

David Dunham
David Dunham

Reputation: 8329

How would the runtime be able to track down all such references?

MyClass* a = [MyClass new];
MyClass* aCopy = a;
[a release];
a = nil;  // Tidy up
[aCopy crashNowPlease];

Sometimes you can catch this sort of thing with Build & Analyze.

Also, you will be able to use zeroing weak references in the future (or, Mike Ash created such a facility).

Upvotes: 3

Mike DeSimone
Mike DeSimone

Reputation: 42795

Because pointers are passed by value and not reference. All dealloc gets is a local copy of the pointer; any changes it makes are discarded. Same goes for C's free and C++'s delete.

Upvotes: 7

Related Questions