Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: block copied and added to mutable array, do I need to release them when empty the array?

So if I have:

SomeBlock myBlock = ^(){};
[self.mutableArray addObject: [myBlock copy] ];

later if I need to:

[self.mutableArray removeAllObjects];

then should I first go through all the blocks in the array and release each of them?

Thanks

Edit:

I am not using ARC, and I saw somewhere when I add a block to array I need to copy it, that's why I do [block copy] when I add it to array, thus I thought that I should release them before I remove all objects from the array.

like image 204
hzxu Avatar asked Jan 30 '26 23:01

hzxu


1 Answers

I am assuming that you are not using ARC (the question would not be interesting then).

In your code, you do need to send release to all of your blocks:: although NSArray retains objects placed into it, and releases objects when the array itself is released, the objects that you add already have a retain count of 1, because copy method gives you an object with a retain count of 1. That is why you need to follow copy with autorelease before adding your block to the array, like this:

[self.mutableArray addObject: [[myBlock copy] autorelease]];
like image 117
Sergey Kalinichenko Avatar answered Feb 01 '26 15:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!