参考了BlockUI,把自己理解的思路做下笔记
首先是对于类的消息传递
必须导入<objc/runtime.h>
对NSObject建立自己的分类NSObject (ZXObject),构建方法
我首先理解的是
const char ZXObjectEventHandlerDictionary;
- (void)handlerEventWithBlock:(id)block withIdentifier:(NSString *)identifier
{
NSAssert(identifier != nil, @"identifier can't be nil.");
NSMutableDictionary *eventHandlerDictionary = objc_getAssociatedObject(self, &ZXObjectEventHandlerDictionary);
if(eventHandlerDictionary == nil)
{
eventHandlerDictionary = [[NSMutableDictionary alloc] init];
objc_setAssociatedObject(self, &ZXObjectEventHandlerDictionary, eventHandlerDictionary, OBJC_ASSOCIATION_RETAIN);
}
[eventHandlerDictionary setObject:block forKey:identifier];
}
返回一个block的引用
- (id)blockForEventWithIdentifier:(NSString *)identifier
{
NSAssert(identifier != nil, @"identifier can't be nil");
NSDictionary *eventHandlerDictionary = objc_getAssociatedObject(self, &ZXObjectEventHandlerDictionary);
if(eventHandlerDictionary == nil) return nil;
return [eventHandlerDictionary objectForKey:identifier];
}
在ViewController_1中有一个Label,一个Button,Button跳转到ViewController_2中,ViewController_2中有一个TextField,一个Button,然后通过navigationController返回到ViewController_1
ViewController_1的Button绑定的事件处理方法,这里是ViewController_1处理从ViewController_2发送过来的消息
- (IBAction)showInput:(id)sender {
InputViewController *input = [[InputViewController alloc] initWithNibName:@"InputViewController" bundle:nil];
input.navigationItem.title = @"input";
[input handlerEventWithBlock:^(NSString *value1,NSString *value2){
NSLog(@"%@",value1);
NSLog(@"%@",value2);
}
withIdentifier:@"custom block"];
[self.navigationController pushViewController:input animated:YES];
}
在ViewController_2的Button绑定的事件处理方法,ViewController_2发送消息,ViewController_1接收到消息,然后处理
- (IBAction)confirm:(id)sender {
void(^block)(NSString *,NSString *) = [self blockForEventWithIdentifier:@"custom block"];
block(@"I'm the first value", @"I'm the second value");
[self.navigationController popViewControllerAnimated:YES];
}
总结下:在ViewController间传递消息可以在用通过构建一个block来,把要传递的数据放到block中,然后在另外一个ViewController中用HandlerEventWithBlock:来对传递过来的数据进行进一步处理,当然这一切都要有一个共同的identifier