IOS uses block to implement function callbacks

Source: Internet
Author: User

In fact, the block in iOS is a function pointer in C + +, the implementation is the same way, a simple practice is posted below.

First, create a callback class

BlockStudy.h

  blockstudy.h//  blockstudy////  Created by du Jia Li on 11/11/14.//  Copyright (c) 2014 DuPont. All rights reserved.//#import <Foundation/Foundation.h> @interface blockstudy:nsobjecttypedef Void (^testblock) (); @property (nonatomic, Strong) Testblock testblock;-(void) startblock; @end
Blockstudy.m

  blockstudy.m//  blockstudy////  Created by du Jia Li on 11/11/14.//  Copyright (c) 2014 DuPont. All rights reserved.//#import "BlockStudy.h" @implementation blockstudy-(void) test{    if (_testblock) {        _ Testblock ();    }} -(void) startblock{    [self performselector: @selector (Test) Withobject:nil afterdelay:2.0];} @end


Call Class VIEWCONTROLLER.M

  viewcontroller.m//  blockstudy////  Created by du Jia Li on 11/11/14.//  Copyright (c) 2014 DuPont. All rights reserved.//#import "ViewController.h" #import "BlockStudy.h" @interface Viewcontroller () @ End@implementation viewcontroller-(void) viewdidload {    [super viewdidload];    Additional setup after loading the view, typically from a nib.    Blockstudy *block = [[Blockstudy alloc] init];    Block.testblock = ^ ()    {        Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Block learning" message:@ "Test succeeded" Delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil];        [Alert show];            };    [Block Startblock];} -(void) didreceivememorywarning {    [super didreceivememorywarning];    Dispose of any resources the can be recreated.} @end






IOS uses block to implement function callbacks

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.