参考了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];
}