Block实现委托机制

本文深入探讨了iOS开发中Block的基本概念、基本用法,包括如何使用Block进行函数式编程,并通过实例展示了如何利用Block实现委托模式。文章详细解释了Block的创建、传递、使用以及在实际开发中的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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;}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值