步骤:
1.给B类添加属性
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;
2.如何调用方法
[self.target performSelector:self.action];
3.如何在A类调用
设置B类所生成的对象.target = self;
设置B类所生成的对象.action = @selector(A类中的方法C);
4.在A类中添加方法C
- (void)C
{
NSLog(@"========");
}
代码例子:
TestView.h
//
// TestView.h
// target-action设计模式
//
// Created by 萨斯辈的呼唤 on 14-6-10.
// Copyright (c) 2014年 萨斯辈的呼唤. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TestView : UIView
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;
@end
TestView.m
//
// TestView.m
// target-action设计模式
//
// Created by 萨斯辈的呼唤 on 14-6-10.
// Copyright (c) 2014年 萨斯辈的呼唤. All rights reserved.
//
#import "TestView.h"
@implementation TestView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.target performSelector:self.action];
}
@end
在MainViewController.m中
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
TestView *test = [[TestView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
test.backgroundColor = [UIColor redColor];
[self.view addSubview:test];
test.target = self;
test.action = @selector(show);
}
- (void)show
{
NSLog(@"========");
}