views:

57

answers:

2

I am just curious if the order expressed for the release of objects should reflect the reverse of their order in the hierarchy:

// Psuedo code
alloc OBJ_001;
alloc OBJ_001 > OBJ_002;
alloc OBJ_001 > OBJ_002 > NSSting;

release NSString;
release OBJ_002;
release OBJ_001;

I am pretty sure it should (makes sense to me), but have not seen any mention of this in my learning so far.

Gary

A: 

I wouldn't say so, as long as you're done using it you can release it whenever you want.

JoePasq
+1  A: 

It doesn't matter. I assume you mean that OBJ_001 owns OBJ_002 owns the NSString instance, and you own all three objects (co-owning the NSString with OBJ_002 and co-owning OBJ_002 with OBJ_001).

Doing it in reverse order:

  1. Release NSString instance: Nothing happens, because OBJ_002 still owns it.
  2. Release OBJ_002: Nothing happens, because OBJ_001 still owns it.
  3. Release OBJ_001: It releases OBJ_002, which releases the NSString. All three dealloc.

Doing it in the same order:

  1. Release OBJ_001: It releases OBJ_002, then deallocks. OBJ_002 still exists because you still own it.
  2. Release OBJ_002: It releases the NSString, then deallocks. The NSString still exists because you still own it.
  3. Release NSString instance: It deallocks.

Either way, all three instances dealloc. There is no difference.

I prefer the reverse order, but that's purely a style choice.

Peter Hosey
The one gotcha is if you have order dependencies in your -dealloc methods. In short, don't have order dependencies in your -dealloc! methods. Or, better yet, turn on GC and be done with it (if targeting Mac OS X).
bbum