在ios开发过程中,经常会遇到A类调用B类的某一个方法,调用完B类方法之后,再执行A类中的其他方法的操作。
通常的做法有两种:
1、通过Delegete来实现;
2、通过通知NSNotificaitionCenter的方式实现;
由于这两种方式比较常见所以就不在解释其使用方法了,这里重点说一下自定义的方式(由方式1简化而来的):
自定义方式实现回调 具体代码:
1、创建一个工程名CallBackDemo,在ViewController.xib文件加入一个button按钮,ViewController.h代码:
1: #import <UIKit/UIKit.h>
2:
3: @interface ViewController : UIViewController{
4: IBOutlet UIButton *clickButton;
5: }
6:
7: - (IBAction)onClickButtonTouchUpInside:(id)sender;
8:
9: @end
上述第7行代码,便是点击button触发的事件操作。
2、ViewController.m代码:
1: //
2: // ViewController.m
3: // CallBackDemo
4: //
5: // Created by jordy on 11-10-28.
6: // Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
7: //
8:
9: #import "ViewController.h"
10: #import "EventObject.h"
11:
12: @implementation ViewController
13:
14:
15: - (void)viewDidLoad
16: {
17: [super viewDidLoad];
18: }
19:
20: - (IBAction)onClickButtonTouchUpInside:(id)sender
21: {
22: NSLog(@"onClickbutton...");
23: EventObject *eventObject = [[[EventObject alloc] init] autorelease];
24: [eventObject setDelegateObject:self setBackFunctionName:@"handleBackFunction"];
25: [eventObject handleEventObject];
26: }
27:
28: - (void)handleBackFunction
29: {
30: NSLog(@"执行完eventObject函数之后的具体的操作。。。。");
31: }
32:
33: - (void)viewDidUnload
34: {
35: [super viewDidUnload];
36: }
37:
38: @end
此类使用到了EventObject类,下面看一下EventObject类的代码。
3、EventObject.h代码:
1: @interface EventObject : NSObject {
2: id callbackObject;//回调类
3: NSString *callbackFunction; //回调的函数名
4: }
5:
6: - (void)handleEventObject;
7:
8: - (void)setDelegateObject:(id)cbobject setBackFunctionName:(NSString *)selectorName;
EventObject.m代码:
1: #import "EventObject.h"
2:
3: @implementation EventObject
4:
5: - (void)handleEventObject
6: {
7: NSLog(@"执行本类的操作");
8:
9: //执行回调操作
10: SEL func_selector = NSSelectorFromString(callbackFunction);
11: if ([callbackObject respondsToSelector:func_selector]) {
12: NSLog(@"回调成功...");
13: [callbackObject performSelector:func_selector];
14: }else{
15: NSLog(@"回调失败...");
16: }
17:
18: }
19:
20: //赋值回调
21: - (void)setDelegateObject:(id)cbobject setBackFunctionName:(NSString *)selectorName
22: {
23: callbackObject = cbobject;
24: callbackFunction = selectorName;
25: }
26:
27: - (void)dealloc
28: {
29: [super dealloc];
30: }
具体说明:
点击button触发 onClickButtonTouchUpInside函数,此函数中调用EventObject类的handleEventObject函数,当执行完handleEventObject函数,回调ViewController类中的handleBackFunction函数。