gyozo kudor
gyozo kudor

Reputation: 6335

When do I need to copy a block?

I don't really know when do I need to copy a block.
The documentation says when you expect the block to be used after destruction of the scope within which it was declared.

Do I need to copy it when I'm using them as callback methods for example? By copy I mean creating a copy property for my block and saving the block there or somehow sending a copy message. The scope is probably destroyed when a download or something similar is finished. So do I need to copy the block in that case? Can I create circular references this way?

Right now I have a downloader class (to test blocks only, it's too dangerous for me to use it yet) that uses a completion block and when I copy the block the view controller that created the block and the downloader class is not released.

Can you give me some good examples especially using them for finishing async operations like file downloads?

Thanks.

Upvotes: 4

Views: 1200

Answers (1)

cobbal
cobbal

Reputation: 70733

Most of the time methods that take callbacks will copy the block for you

I can think of two cases when you need to copy a block yourself in Objective-C

  • when you're returning a block from a function
  • when you're saving a block to a class variable (this is the case that happens when you're implementing a method that accepts a callback at a later point).

Since these are the times the block will drop out of scope before they're used or dealt with.

Upvotes: 6

Related Questions