一、Block的基本概念
Block是程序的代码块,这个代码块可以在需要的时候执行。IOS开发中,block到处可见,所以学好很重要
二、Block的基本用法
//
// main.m// Block//
// Created by Joe on 15-2-23.// Copyright (c) 2015年 apple. All rights reserved.//#import <Foundation/Foundation.h>//最基本的用法
void test(){
{
int (^Sum)(int, int) = ^(int a, int b) {
{
return a + b; }; NSLog(
};
NSLog(@"%d", 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(
NSLog(@"%d", c);}}//改变外边变量的值
void test2(){ __block
{
__block int mul = 7;
int (^myBlock)(int) = ^(int num) { mul
{
mul = 10; NSLog(
NSLog(@"mul is %i", mul);
return mul * num; };
};
int c = myBlock(7); NSLog(
NSLog(@"%d", c);}}//给block起一个别名,之后我们就可以任意命名的来使用block
void test3(){ typedef
{
typedef int (^MySum)(int, int); MySum sum
MySum sum = ^(int a, int b) {
{
return a + b; };
};
int c = sum(20, 39); NSLog(
NSLog(@"%d", c); }
}int main(int argc, const char * argv[]){ @autoreleasepool { test(); }
{ @autoreleasepool {
test();
}
return 0;}
}
OK,都有注释。在main函数中调用即可测试
三、Block来实现委托模式
//
// Button.h// Block_Button//
// Created by JOe on 15-3-23.// Copyright (c) 2015年 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 JOe on 15-3-23.
// Copyright (c) 2015年 apple. All rights reserved.
// #import " Button.h " @implementation Button // 模拟点击-( void )click{
{
// 回调函数,回调block
_block(self);
} @end
//
// main.m // Block_Button //
//
// Created by JOe on 15-3-23.
// Copyright (c) 2015年 apple. All rights reserved.
// #import <Foundation/Foundation.h>#import " Button.h " int main( int argc, const char * argv[]){ @autoreleasepool { Button
{ @autoreleasepool {
Button *btn = [[[Button alloc] init] autorelease];
// 回调的函数
btn.block = ^(Button * btn) { NSLog(
{
NSLog( @" %@被点击 " , btn); }; [btn click]; }
};
[btn click];
}
return 0 ;}
}