代理、block、通知中心传值

本文深入探讨了iOS开发中三种常用通信机制:代理、Block及通知中心的使用方法。详细介绍了代理模式的定义与实现,Block的声明与调用,以及通知中心的发布与订阅机制。

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

1.代理
委托者.h文件

@protocol DBDoorHoneListTabCollectionCellDelegate <NSObject>
- (void)selectedItemButton:(NSInteger)index;

@end

@interface DBDoorHoneListTabCollectionCell : UITableViewCell
@property(nonatomic,weak)id<DBDoorHoneListTabCollectionCellDelegate>   DBDoorHoneListTabCollectionCellDelegate;

@end
委托者.m文件
if(self.DBDoorHoneListTabCollectionCellDelegate&&[self.DBDoorHoneListTabCollectionCellDelegate respondsToSelector:@selector(selectedItemButton:)]) {
       [self.DBDoorHoneListTabCollectionCellDelegate selectedItemButton:indexPath.row];

}

代理控制器.m

 listColCell.DBDoorHoneListTabCollectionCellDelegate = self;
 - (void)selectedItemButton:(NSInteger)index
{
    doorRow = index;
}


2.block

声明.h
 

typedef void (^ReturnTextBlock)(NSString *showText);//给block重命名,方便调用
@interface B : UIViewController
@property (nonatomic, copy) ReturnTextBlock returnTextBlock;//声明一个block属性
- (void)returnText:(ReturnTextBlock)block;//加上后方便第A视图书写该block方法

声明.m
- (void)returnText:(ReturnTextBlock)block {
self.returnTextBlock = block;

}
 if (self.returnTextBlock != nil) {
self.returnTextBlock(self.inputTF.text);


调用.m

[bVC returnText:^(NSString *showText) {
    self.showLabel.text = showText;
}];

 

3.通知中心
 [[NSNotificationCenter  defaultCenter]postNotificationName:@"currentItemIndex" object:@(index)];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(currentItemIndex:) name:@"currentItemIndex" object:nil];

-(void )currentItemIndex:(NSNotification*)not{
     NSInteger deviceId = [not.object integerValue];

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值