您的位置:首页 > 其它

OC之Block的用法和实现委托

2014-03-26 19:17 344 查看
Block的基本概念

Block的基本用法

Block实现委托机制

一、Block的基本概念

Block是程序的代码块,这个代码块可以在需要的时候执行。IOS开发中,block到处可见,所以学好很重要

二、Block的基本用法

//
//  main.m
//  Block
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>

//最基本的用法
void test()
{
int (^Sum)(int, int) = ^(int a, int b)
{
return a + b;
};

NSLog(@"%i", Sum(10, 11));
}

//也是基本用法,另外Block代码段中可以使用外边的mul变量,但是不可以改变他的值,如果下改变他的值,可以使用__block来定义mul
void test1()
{
int mul = 7;
int (^myBlock)(int) = ^(int num)
{
return mul * num;
};

int c = myBlock(7);

NSLog(@"%i", c);
}

//改变外边变量的值
void test2()
{
__block int mul = 7;
int (^myBlock)(int) = ^(int num)
{
mul = 10;
NSLog(@"mul is %i", mul);
return mul * num;
};

int c = myBlock(7);

NSLog(@"%i", c);
}

//给block起一个别名,之后我们就可以任意命名的来使用block
void test3()
{
typedef int (^MySum)(int, int);

MySum sum = ^(int a, int b)
{
return a + b;
};

int c = sum(20, 39);

NSLog(@"%i", c);

}

int main(int argc, const char * argv[])
{

@autoreleasepool {
test();
}
return 0;
}


OK,都有注释。在main函数中调用即可测试

三、Block来实现委托模式

//
//  Button.h
//  Block_Button
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>
@class Button;

//给block给一个别名ButtonBlock
typedef void (^ButtonBlock)(Button *);

@interface Button : NSObject

//定义一个block的成员变量,暂时写成assign
@property (nonatomic, assign) ButtonBlock block;

-(void)click;

@end


//
//  Button.m
//  Block_Button
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Button.h"

@implementation Button

//模拟点击
-(void)click
{
//回调函数,回调block
_block(self);
}

@end


//
//  main.m
//  Block_Button
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Button.h"

int main(int argc, const char * argv[])
{

@autoreleasepool {

Button *btn = [[[Button alloc] init] autorelease];

//回调的函数
btn.block = ^(Button *btn)
{
NSLog(@"%@被点击", btn);
};

[btn click];

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: