標籤:ios target-action模式 iphone
該模式主要是為了減少模組之間代碼耦合性,以及增強模組內代碼之間的內聚性.
讓我們來看看一個執行個體:
1:假設有這麼一個需求:我們點擊一個視圖對象,可以改變該視圖的顏色,這個對於初學者來說是一件非常容易做到的事,只要在這個視圖類中重寫:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event函數,然後改變該視圖的背景色即可,可是這時候又有了新的需求,一部分人需要在點擊該視圖改變該視圖的顏色,一部分人需要在點擊該視圖時改變該視圖的位置,為了讓不同對象執行不同的事件,在執行個體化該視圖類對象時需要指定該對象感興趣的事件,對於這個需求我們可以通過定義枚舉變數作為該對象的資料成員,並在初始化的時候指定枚舉值(即指定感興趣的事件),同時需要重寫-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event函數,讓它對不同的枚舉值,執行不同的功能,假設這個時候我們又需要在點擊該視圖對象時,執行一個翻轉功能,我們得又去修改該視圖內的具體實現功能,這樣代碼之間的耦合性就比較大,移植起來就很不方便(試想這樣的一個情境,假設別人的app需要你寫好的這個視圖類,但是別人不需要你視圖類中事件方法,則需要修改該視圖類,難免發生一些錯誤),解決這個問題的方法就是Target-Action模式,直接看代碼:
//主視圖標頭檔
#import <UIKit/UIKit.h>@interface MainViewController : UIViewController@end
//主視圖實現
#import "MainViewController.h"#import "MyView.h"@implementation MainViewController-(id)init{ self= [super init]; if (self) { } return self;}-(void)viewDidLoad{ MyView * view1 = [[MyView alloc]initWithFrame:CGRectMake(10, 20, 100, 100) andTarget:self andAction:@selector(changeColor:)]; [self.view addSubview:view1]; MyView * view2 = [[MyView alloc]initWithFrame:CGRectMake(10, 20, 100, 100) andTarget:self andAction:@selector(moveFrame:)]; [self.view addSubview:view2]; }-(void)changeColor:(UIView *)aView{ NSLog(@"buttonClick"); int red = arc4random()%255; int green = arc4random()%255; int blue = arc4random()%255; aView.backgroundColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];}-(void)moveFrame:(UIView *)aView{ aView.frame = CGRectMake(arc4random()%320, arc4random()%480, 100, 100);}@end
//測試檢視類標頭檔
#import <UIKit/UIKit.h>@interface MyView : UIView{ id _target; SEL _action;}-(id)initWithFrame:(CGRect)frame andTarget:(id)target andAction:(SEL)action;@property (assign,readwrite,nonatomic)id deledate;@end
////測試檢視類實現
#import "MyView.h"@implementation MyView-(id)initWithFrame:(CGRect)frame andTarget:(id)target andAction:(SEL)action{ self = [super initWithFrame:frame]; if (self) { _target = target; _action = action; } self.backgroundColor = [UIColor blueColor]; return self;}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [_target performSelector:_action withObject:self];}@end
總結:從上面的代碼中可以看出模組與模組之間的耦合性很低,無論想要添加什麼功能事件,都不需要修改視圖類!
本文出自 “網路學習總結” 部落格,請務必保留此出處http://8947509.blog.51cto.com/8937509/1575847
IOS開發之Target-Action模式