iOS block 代理 通知方法总结

本文总结了iOS开发中关于Block、代理和通知的使用方法。首先介绍了如何声明、调用及实现Block,然后讲解了代理的声明、实现及调用过程,最后讨论了发送和接收通知的操作步骤。

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

一.block

先声明block

<1>声明block

typedef void(^myBlock)(NSString *name);

//<2>声明一个block属性

@property (nonatomic, copy) myBlock block;

 //<3>调用block、传值    

    if (self.block) {

        self.block(@"123");

    }

  //<4>实现block

    //a:NSString *name   代表传过来的值

    next.block = ^(NSString *name){

        //<5>实现

        NSLog(@"%@",name);

        self.view.backgroundColor = [UIColor cyanColor];

    };

二.代理

@protocol NextViewControllerDelegate <NSObject>

-(void)nextViewControllerSendData;

@end


@property (nonatomic,weak) id<NextViewControllerDelegate> delegate;


if ([self.delegate respondsToSelector:@selector(nextViewControllerSendData)]) {

        //代理有实现方法

        [self.delegate nextViewControllerSendData];

    }

//遵守协议

@interface ViewController ()<NextViewControllerDelegate>


next.delegate = self;

-(void)nextViewControllerSendData{


    NSLog(@"nextViewControllerSendData");

}

三通知

//1.发送通知

[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:nil userInfo:@{@"key":[NSString stringWithFormat:@"%ld",_number]}];

//2.接收通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNumber:) name:@"notification" object:nil];

- (void)addNumber:(NSNotification *)noti

{

    UILabel * label = (id)[self.view viewWithTag:10];

    label.text = [NSString stringWithFormat:@"%@",[noti.userInfo objectForKey:@"key"]];   

}

// 3.根据观察者 移除所有通知

    [[NSNotificationCenter defaultCenter] removeObserver:self];





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值