//
// main.m
// OC5_Block
//
// Created by zhangxueming on 15/6/26.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import <Foundation/Foundation.h>
//block
//函数指针
int add(
int a,
int b)
// int (*)(int , int)
{
return a+
b;
}
typedef int (* Padd)(
int,
int);
//block 是OC中的数据类型,用来保存一段代码块
typedef
int(^ addBlock) (
int,
int);
// int (^ ) (int , int)
typedef int (^ MyBlock) (
int,
int);
int main(
int argc,
const char *
argv[]) {
@autoreleasepool {
Padd func=
add;
NSLog(@"add =%i", func(
3,
5));
//不带参数的block
// void (^printBlock)(void)= nil;
// printBlock = ^(void)
// {
// NSLog(@" *");
// NSLog(@" ***");
// NSLog(@"*****");
// };
// NSLog(@"%p", printBlock);
// printBlock();
// printBlock();
//省约(void)
void (^printBlock)(
void) = ^
{
NSLog(@" *");
NSLog(@" ***");
NSLog(@"*****");
};
printBlock();
//带参数的block
int (^minusBlock)(
int,
int)=^(
int a,
int b)
{
return a-
b;
};
NSLog(@"sub = %i", minusBlock(
10,
3));
//block可以直接读取block外部变量, 但是不能修改, 如果要修改block外部变量的值,需要在变量的前面 加 __block关键字
__block int num=
100;
void (^numBlock)(
void)=^
{
NSLog(@"num = %i", num);
};
numBlock();
void (^setNumBlock)(
int) = ^(
int value)
{
num =
value;
NSLog(@"num = %i", num);
};
setNumBlock(200);
//block 与 typedef
MyBlock multiBlock = ^(
int a,
int b)
{
return a*
b;
};
NSLog(@"mul = %i", multiBlock(
10,
6));
}
return 0;
}
转载于:https://www.cnblogs.com/0515offer/p/4602264.html
转载请注明原文地址: https://win8.8miu.com/read-1541801.html