你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 使用Block實現函數回調

iOS 使用Block實現函數回調

編輯:IOS開發綜合

其實,iOS中的Block就是C++中的函數指針,實現方式都是一樣的,下面貼出一個簡單的實踐。

首先,創建一個回調的類

BlockStudy.h

//
//  BlockStudy.h
//  BlockStudy
//
//  Created by 杜甲 on 11/11/14.
//  Copyright (c) 2014 杜甲. All rights reserved.
//

#import 

@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






  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved