5

Why should bloc properties be declared as copy?

typedef void(^Thunk)(void);
@property (nonatomic, copy) Thunk block;

Why is it necessary to make a copy of the block object?

Scott Berrevoets
  • 16,921
  • 6
  • 59
  • 80
cfischer
  • 24,452
  • 37
  • 131
  • 214

3 Answers3

4

If you're going to use the block outside of the scope where it was defined, you need to make a copy of it, because that copies it to the heap. The original block is allocated on the stack, and so it will be deallocated when it goes out of scope, aka when the method or block of code that it was defined in finishes. Most often blocks are used for asynchronous activities, so often you need to do this.

Gavin
  • 8,204
  • 3
  • 32
  • 42
3

Because a block literal is created on the stack and will be destroyed when the function exits. When keeping a block around it's necessary to copy it.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • Shouldn't it also be declared as weak, in case sit captures self (to avoid a retain cycle)? – cfischer Feb 19 '14 at 17:45
  • 1
    @cfisher That would mean that somebody else had to keep a strong reference on the block. Also `copy`/`weak` are by definition mutually exclusive. The common solution is not to capture the owner strongly in the block. – Nikolai Ruhe Feb 19 '14 at 18:04
1

A block is created on the stack and captures state to a stack allocation. You need to perform the copy to:

  • copy the block
  • copy its captured state
  • and form strong references to objc_objects

…so that you may safely use the block outside of the lexical scope it was created in.

justin
  • 104,054
  • 14
  • 179
  • 226