ios学习笔记(六)之回调函数

本文主要介绍了在Objective-C中使用回调函数的过程,包括创建协议、定义回调方法以及实现回调函数的注册和调用。通过一个实例展示了类A如何通过类B的回调功能接收并处理结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天开发中用到了回调,貌似oc中回调方法很多,在此仅先学习来正式协议回调。


回调函数: 

类A调用类B, 类B某个模块之行结束需要调用A中的某个函数 


通常有两个步骤: 

- 回调函数注册   类A将自己的函数作为回调函数注册到B 

- 函数调用,类B中达到某个条件时调用类A注册到类B的回调函数


第一步创建协议

#import <Foundation/Foundation.h>

@protocol ASIhttpCallback


-(NSString*) httpSuccess:(NSString*) result;

-(NSString*) httpFailures:(NSString *) result;

@end


步骤二  创建类B  运行回调函数 

classB.h 

@interface MalertViewUtil : NSObject{ 

                   id<ASIhttpCallback> asihttpCallback;

@property (nonatomic) id<ASIhttpCallback> asihttpCallback;

-(void)test;

@end


classB.m

@implementation ClassB

-(void)test{

   [self.asihttpCallback httpSuccess:传入值];//调用回调函数

}

@end


第三步  类A进行回调函数注册

classA.h

#import "ASIhttpCallback.h"

@interface classA : UIViewController<ASIhttpCallback>

-(void)classAtest; 

@end


classA.m 

@implementation classA

(NSString*) httpSuccess:(NSString*) result

{

    NSLog(@"回调结果:%@",result);

    return NULL;

}

-(NSString*) httpFailures:(NSString *) result

{

    return NULL;


}

-(void)classiest{

  classB *classBtest = [[classB alloc] init];

  classBtest.delegate = self;

}

@end









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值