gpt4 book ai didi

ios - 如何在 IOS 中将回调方法作为参数传递

转载 作者:行者123 更新时间:2023-11-29 02:31:39 31 4
gpt4 key购买 nike

我将根据下面的例子解释需求

这是异步操作后需要调用的方法

    -(void) myCallbackMethodOne: (NSString *)response
{
//method to be called
}

-(void) myCallbackMethodTwo: (NSString *)response
{
//method to be called
}



-(void) getDataFromServerWithCallback: (NSString *)requestString _Callback(CallbackMethod *) methodName
{
//logic to send request and
//to set callback method something similar to
[setCallbackMethod methodName];
}

-(void) onDataRecievedFromServerWithResponse: (NSString *) response //this method gets called as part of framework
{
[callTheCallbackMethod: response];
}

调用方法来演示需求的地方

    -int main()
{
[getDataFromFromServerWithCallback: @"getTopNews" _Callback:myCallbackMethodOne]; //this is the requirement; I should be able to pass myCallbackMethod as argument

[getDataFromFromServerWithCallback: @"getBusinessNews" _Callback:myCallbackMethodTwo]; //this is the requirement; I should be able to pass myCallbackMethod as argument

}

最佳答案

此类功能有两种成熟的模式:

1) 委托(delegate):

@protocol ResponseDelegate
- (void)handleResponse:(NSString *)response;
@end

@interface CommsClass : NSObject
@property (weak) id<ResponseDelegate> delegate;
- (void)sendRequest:(NSString *)request;
@end

@interface CallingClass : NSObject <ResponseDelegate>
{
CommsClass _commsClass;
}

- (void)callingCode;
@end

@interface CallingCode

- (void)callingCode
{
_commsClass = [CommsClass new];
_commsClass.delegate = self;
[_commsClass sendRequest:@"Blah"];
}

- (void)handleResponse:(NSString *)response
{
NSLog(@"Whoot: %@", response);
}

@end

2) block 。

typedef (^HandleResponseBlock)(NSString *response);

@interface CommsClass : NSObject
- (void)sendRequest:(NSString *)request
withCompletionBlock:(HandleResponseBlock)block;
@end

关于ios - 如何在 IOS 中将回调方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26778798/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com