IOS block programming considerations

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.