导入runtime扩展NSObject,利用block在ViewController中来进行消息传递

参考了BlockUI,把自己理解的思路做下笔记

首先是对于类的消息传递

必须导入<objc/runtime.h>

对NSObject建立自己的分类NSObject (ZXObject),构建方法

我首先理解的是

const char ZXObjectEventHandlerDictionary; // 用来表示

- (void)receiveObject:(void(^)(id object))sendObject withIdentifier:(NSString *)identifier
{
    NSAssert(identifier != nil, @"identifier can't be nil.");
    NSMutableDictionary *eventHandlerDictionary = objc_getAssociatedObject(self, &ZXObjectSingleObjectDictionary);
    if (eventHandlerDictionary == nil)
    {
        eventHandlerDictionary == [[NSMutableDictionary alloc] init];
        objc_setAssociateObject(self, &ZXObjectSingleObjectDictionary, eventHandlerDictionary, OBJC_ASSOCIATION_RETAIN);
    }
    [eventHandlerDictionary setObject:sendObject forKey:identifier];
}
- (void)sendObject:(id)object withIdentifier:(NSString *)identifier
{
    NSAssert(identifier != nil, @"identifier can't be nil");
    NSDictionary *eventHandlerDictionary = objc_getAssociatedObject(self, &ZXObjectSingleObjectDictionary);
    if (eventHandlerDictionary == nil)
	return;
    void(^block)(id object) = [eventHandlerDictionary objectForKey:identifier];
    block(object);
}


在ViewController_1中有一个Label,一个Button,Button跳转到ViewController_2中,ViewController_2中有一个TextField,一个Button,然后通过navigationController返回到ViewController_1

ViewController_1的Button绑定的事件处理方法

- (IBAction)showReceiveMsg:(id)sender
{
    ViewController_1 = [[ViewController_1 alloc] init];
   [ ViewController_1 receiveObject:^(id object){
	Label.text = object;
    } withIdentifier:@"InputFinish"];	//InputFinish要与sendObject withIdentifier中的InputFinish一致,否则收不到消息
}

在ViewController_2的Button绑定的事件处理方法

- (IBAction)handleSendMsg:(id)sender
{
    [self sendObject:TextField.text withIdentifier:@"InputFinish"];
    [self.navigationController popViewControllerAnimated:YES];
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值