Target-Action模式是ObjC里非常常见的对象之间方法调用的方式,不过ObjC把方法调用叫做Send Message.
一帮情况在和UI打交道时候处理各种GUI上的事件会利用到这种模式.相对应的.NET上的处理模式就是delegate/event了. 不过,Target-Action拜C语言所赐,更是灵活很多,编译期没有任何检查,都是运行时的绑定.
代码演示:
1.创建一个继承UIView的类
#import <UIKit/UIKit.h>
@interface TouchView : UIView
//模拟的Button的写法
//实现方法的独享
@property (nonatomic,assign) id target ;
//实现的方法
@property (nonatomic,assign) SEL action ;
@end
实现部分:
@implementation TouchView
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//self.target 实现self.action的方法
//withObject:一般用来实现多线程之间的通信
[self.target performSelector:self.action withObject:self];
}
@end
初始化:
#import "RootViewController.h"
#import "TouchView.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
// target / action
/*
面向对象编程的核心思想:高内聚,低耦合
target/action:可以用来解耦
*/
TouchView *touchView1 = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 175, 100)];
touchView1.backgroundColor = [UIColor magentaColor];
TouchView*touchView2 = [[TouchView alloc]initWithFrame:CGRectMake(100, 250, 175, 100)];
touchView2.backgroundColor = [UIColor redColor];
//对target赋值
touchView1.target = self ;
//指定要实现的方法,对action赋值
touchView1.action = @selector(touchAction1:);
touchView1.tag = 111 ;
[self.view addSubview:touchView1];
[touchView1 release];
touchView2.target = self ;
touchView2.action =@selector(touchAction2:) ;
touchView2.tag = 222 ;
[self.view addSubview:touchView2];
[touchView2 release];
}
-(void) touchAction1:(TouchView *)touchView
{
TouchView *tempTouchView = (TouchView *)[self.view viewWithTag:111];
tempTouchView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:arc4random()%256/255.0];
}
-(void) touchAction2:(TouchView *)touchView{
TouchView *tempTouchView1 = (TouchView *)[self.view viewWithTag:222];
// tempTouchView1.center = CGPointMake(arc4random() %180 +90, arc4random() %567 + 50);
tempTouchView1.frame = CGRectMake(arc4random() %201, arc4random() % 568, 175, 100);
}
@end