zoukankan      html  css  js  c++  java
  • iOS 使用Block实现函数回调

    事实上。iOS中的Block就是C++中的函数指针,实现方式都是一样的,以下贴出一个简单的实践。

    首先,创建一个回调的类

    BlockStudy.h

    //
    //  BlockStudy.h
    //  BlockStudy
    //
    //  Created by 杜甲 on 11/11/14.
    //  Copyright (c) 2014 杜甲. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    @interface BlockStudy : NSObject
    
    typedef void (^TestBlock)();
    @property (nonatomic , strong) TestBlock testBlock;
    
    
    - (void)StartBlock;
    @end
    
    BlockStudy.m

    //
    //  BlockStudy.m
    //  BlockStudy
    //
    //  Created by 杜甲 on 11/11/14.
    //  Copyright (c) 2014 杜甲. 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
    


    调用类ViewController.m

    //
    //  ViewController.m
    //  BlockStudy
    //
    //  Created by 杜甲 on 11/11/14.
    //  Copyright (c) 2014 杜甲. All rights reserved.
    //
    
    #import "ViewController.h"
    #import "BlockStudy.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        BlockStudy *block = [[BlockStudy alloc] init];
        block.testBlock = ^()
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Block学习" message:@"測试成功" delegate:self cancelButtonTitle:@"取消吧" otherButtonTitles:@"OK", nil];
            [alert show];
            
        };
        [block StartBlock];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    






  • 相关阅读:
    react:如何创建一个新项目
    python3-多重继承
    Stylus-富有表现力的、动态的、健壮的CSS
    使用@property
    python3-使用__slots__
    python:实例属性和类属性
    java_day1
    学习笔记144—SPSS 重复测量方差分析【方法二】
    学习笔记143—SPSS 重复测量的多因素方差分析
    学习笔记142—Matlab如何读取Excel和写入Excel??
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5163440.html
Copyright © 2011-2022 走看看