ios中利用协议实现回调函数功能
来源:互联网 发布:淘宝旗袍模特最红 编辑:程序博客网 时间:2024/05/25 12:22
最近因为项目中需要实现回调函数功能,所以学习了下在ios中如何实现回调函数的相关知识。我们知道在C/C++中回调函数是通过函数指针来实现的,在ios中我们可以通过协议来实现回调功能,另外还可以通过委托以及通知来实现此功能,下面通过一个Demo来说明具体实现过程。此Demo包括ViewController类和ReceiveData类两个类以及自定义协议RefreshText协议。ViewController类实现视图界面,ReceiveData类实现数据的获取,当获取数据成功后调用协议中定义的函数-(void)refreshWithString:,这个函数将会在ViewController中实现,从而改变文本视图中的内容,达到回调函数的功能。具体实现步骤如下:
一、新建工程Test_CallBack,定义协议RefreshText:
@protocol RefreshText <NSObject>
-(void)refreshWithString:(NSString*)str_text; // 强制实现方法
@optional
-(void)showHello; //可选实现方法
@end
二、ViewController视图中添加一个UIButton和UITextField控件,button实现-(IBAction)starCallBack:(id)sender方法,ViewCon.h定义如下:
#import <UIKit/UIKit.h>
#import "RefreshText.h" //引入协议头文件
@interface ViewController : UIViewController<RefreshText> //定义遵循RefreshText协议,
这时类中就必须要实现-(void)refreshWithString:方法
@property (nonatomic, retain) IBOutlet UITextField *text;
-(IBAction)starCallBack:(id)sender;
@end
ViewControll.m文件实现如下:
#import "ViewController.h"
#import "ReceiveData.h" //引入数据获取类ReceiveData头文件,此类中一旦获取数据就会调用回调函数更新视图
@implementation ViewController
@synthesize text;
-(IBAction)starCallBack:(id)sender
{
ReceiveData *recData=[[ReceiveData alloc]init];
recData.delegate=self; delegate定义在ReceiveData类中:id <RefreshText> delegate;
[recData initTextString]; //initTextString方法是ReceiveData类中定义的方法,用来实现数据获取
[recData release];
}
-(void)refreshWithString:(NSString *)str_text
{
self.text.text=str_text; //更新文本框内容
}
三、新建ReceiveData类
#import <Foundation/Foundation.h>
#import "RefreshText.h"
@interface ReceiveData : NSObject
{
id <RefreshText> delegate;
}
@property (nonatomic, assign) id<RefreshText>delegate;
-(void)initTextString;
@end
#import "ReceiveData.h"
@implementation ReceiveData
@synthesize delegate;
-(void)initTextString
{
NSString *str1=@"利用协议实现回调";
[delegate refreshWithString:str1]; //调用协议方法
}
@end
四、测试,运行程序,点击按钮,文本框中会出现 "利用协议实现回调"文本。
- ios中利用协议实现回调函数功能
- [iOS]Objective-C利用协议实现回调函数(类似java的回调函数)
- [iOS]Objective-C利用协议实现回调函数(类似java的回调函数)
- [iOS]Objective-C利用协议实现回调函数(类似java的回调函数)
- [iOS]Objective-C利用协议实现回调函数(类似java的回调函数)
- [iOS]Objective-C利用协议实现回调函数(类似java的回调函数)
- Objective-C学习笔记 利用协议实现回调函数
- Objective-C利用协议实现回调函数
- Objective-C利用协议实现回调函数
- Objective-c利用协议实现回调函数
- Objective-C利用协议实现回调函数(类似java的回调函数)
- Objective-C利用协议实现回调函数(类似java的回调函数)
- Objective-C利用协议实现回调函数(类似java的回调函数)
- iOS--NSStreamDelegate 的协议来实现 CFNetwork 中的回调函数的作用实现ftp上传下载功能
- 利用回调函数实现有限自动机
- IOS 回调函数实现方法
- ios回调函数
- IOS回调函数
- next_premutation
- java(JNI)调用c/c++动态链接库 linux
- 利用systeminfo命令查看电脑系统安装时间等信息
- vector
- 17款响应式布局框架
- ios中利用协议实现回调函数功能
- 同问 集成网卡和独立网卡哪个好?
- JConsle的简单使用
- Fedora 日志
- C语言文件操作函数大全
- ffmpeg 中关于parse_options()的解析
- 优先级队列
- 集成显卡坏了怎么办
- Entity FrameWork