1. Block declarations and thread safety
The declaration of the block attribute first needs to use the copy modifier, because only the copy block will be in the heap, the life cycle of the block in the stack is bound to the stack, you can refer to the previous article (IOS: Non-arc back block).
Another issue to be aware of is thread safety, which needs to be confirmed when declaring the Block property "is it possible for another thread to modify block when calling block?" "This problem, if it is determined that this does not happen, then the block attribute declaration can be used nonatomic." If you are not sure (usually this is the case), then you first need to declare that the Block property is atomic, that is, to guarantee the atomicity of the variable (OBJECTIVE-C does not enforce the atomic nature of the pointer read and write, C #).
For example, such a block type:
typedef void (^myblocktype) (int);
Attribute declaration:
@property (copy) Myblocktype Myblock;
Here the arc and non-arc declarations are the same, and of course note that the Block is to be release under non-arc.
However, with atomic to ensure that basic atomicity is still not thread-safe, then the block must be assigned to local variables at the time of invocation to prevent the block from suddenly changing. Because if this is not the case, even if you first judge that the Block property is not empty, before the call, once another thread has set the Block property empty, the program will be crash, the following code:
if (Self.myblock)
{
At this point, the Self.myblock may be changed to empty by another thread, causing crash
Note: Atomic only ensures the atomicity of Myblock, which is inherently non-thread-safe.
Self.myblock (123);
}
So the correct code is (ARC):
Myblocktype block = Self.myblock;
Block is now locally immutable.
if (block)
{
Block (123);
}
In the non-arc you need to manually retain, otherwise if the property is empty, the local variable is a wild pointer, the following code:
Non-arc
Myblocktype block = [Self.myblock retain];
if (block)
{
Block (123);
}
[Block release];
Why block with Copy property in iOS