Block can be used as a replacement for delegatge. It is easy to use and does not need to write too much @ protocol to define interfaces. However, pay attention to the following points.
(1) The block is not an object, so it is not valid for the retain. To keep the lifecycle of the block, you 'd better use copy. Remember to release the block after copy. If you do not want to manage them manually, you can use [[testblock] Copy] autorelease] to manage them.
(2) We know the objects of applications normally blocked, and retaincount will automatically add one. To break this retain circle, we can add _ block in front of the object, in this way, the block will not maintain this object. There are two cases
(1) References to temporary variables, for example, a A = [[[A alloc] init] withblock: ^ {
[A Action];
[A release];
}]; In fact, this will cause memory leakage. To break this circle, you only need to add _ block before. In my test code, the program crashes directly because _ block is not added to a_block.
That is
_ Block A = [[[A alloc] init] withblock: ^ {
[A Action];
[A release];
}]; Then the dealloc method of a will call
(2) References to instance variables are as follows:
A A = [[[A alloc] init] withblock: ^ {
[Self Action];
}]; In this way, even if the release method of the self class is called, as long as the block is not executed completely, the self will not be released. To break this kind of practice, we can use the following method:
_ Block typeof (Self) bself = self; that is, it is referenced by expression. For details, refer to typeof usage.
Indicates that bself is of the self type.
A A = [[[A alloc] init] withblock: ^ {
[Bself Action];
}]; In this way, the block and self are independent of each other.