Struggling to get this figured out


#1

I’ve read through the chapter on blocks a few times, maybe 5 now, but I still feel as if I’m not following what’s going on. I’ve got it figured out up till the discussion on “Memory Management”.

What’s confusing me to begin with is why a block would need to live longer than the current stack frame would allow. The book mentions that “it (a block) could become an instance of a variable object” and that it must be copied to the heap if that’s the case. I’m not sure I’m understanding how a block would be an instance variable of an object. Perhaps you could give me an example of this?

There are other sections within this area that I’m not clear on so I may follow up on those if that’s Ok? However this is stumping me as I can’t visualise this at all.


#2

OK, let me give you an example. On iOS, there is a class that plays back video: AVPlayer. Maybe while the video is playing you want a block triggered every 12 frames. So, AVPlayer has a method:

- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block

(ignore the queue argument, that would just blow your mind. :slight_smile: )

So, you can give it a block that will get executed periodically while the movie plays. That block must live for as long as the AVPlayer – it is held by an instance variable of AVPlayer.

How’s that?


#3

Thanks, that helps. I suppose in a sense it seems hard to think about because for the most part everything in the book is done within main. Because of that any blocks that are created don’t really end up being dropped from the stack so that’s never a problem. I imagine that as I get into using blocks more then it may become clearer as to how they use memory and when I need to create a copy on the heap.

Suppose I have a program which creates an object by calling an init method in a class file. As part of the init I create a block specific to the object created. I would need to copy this block because if I didn’t it would disappear once the init method returned, right?


#4

Is the important take away from this that a block is copied if a method takes a block as an argument, and that we need to deal with the fact it’s now on the heap, and the potential for memory issues due to this?


#5

Exactly right.


#6

Great. I feel like I’m finally getting a handle on this.

Would this be how you create a weak pointer outside a block that you could use inside a block to avoid a circular reference?


#7

Is it a good idea to make an array, weak?