1

I have similar question to this: What is the difference between setting object = nil and [object release] VS [object release] and object = nil?

NSMutableArray *myExampleArray = [[NSMutableArray alloc] init];
myExampleArray = nil;

I use iOS 5.0 automatic reference counting, so in fact I don't release any objects. So if I assign it to nil is it equal to [myExampleArray release] ?

I know that i can't later use myExampleArray without re-initial it. So next question. What is the best way to clear this NSArray?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Jakub
  • 12,851
  • 13
  • 75
  • 130

2 Answers2

7

Yes, in an ARC environment you never call release. So assigning nil to the variable will release the object.

In a non ARC environment, you would do a release on your own, so the object gets destroyed. But the variable would still point to the old object adress. But there is no object anymore, so you would probably get a crash (EXC_BAD_ACCESS), if you use the variable later. If you also assign nil to it, that won't happen. Because the variable won't point to the old object address anymore.

Your other question: If you need the array later again, you can call removeAllobjects on a NSMutableArray to remove all added objects, like Ankit Gupta said already. This will result in an empty array, that is still alive, so you can reuse it.

calimarkus
  • 9,738
  • 1
  • 24
  • 47
3

Don't use Nil for your object
try this line:

[myExampleArray removeAllobjects];
MByD
  • 129,681
  • 25
  • 254
  • 263
Ankit Gupta
  • 948
  • 6
  • 19
  • Thanks, but I also want to know what assign to nil does? It is the same as release memory? – Jakub Apr 19 '12 at 08:13
  • @Kuba assigning to `nil` is similar to release memory, but not the same. It will first decrease the reference count, and if that counter is now 0, it will release the memory soon (and not necessarily immediately). Emptying the array is something different: only the elements of the array get affected by the reference count decrease. – Cœur Jul 31 '17 at 02:04