gpt4 book ai didi

ios - 如何实现委托(delegate)代替通知

转载 作者:行者123 更新时间:2023-11-29 00:37:59 24 4
gpt4 key购买 nike

## 网络类

-(void)getResponse:(NSString *)url{

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[urlRequest setHTTPMethod:@"GET"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

NSURLSessionDataTask *task = [session dataTaskWithRequest: urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//check if we encountered an error
if(error != nil){
NSLog(@"%@", [error localizedDescription]);
}else{
//get and check the HTTP status code
NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];
if (HTTPStatusCode != 200) {
NSLog(@"HTTP status code = %ld", (long)HTTPStatusCode);
}

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if(data != nil){
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

[[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadNotification"
object:self
userInfo:responseDictionary];
NSLog(@"The response is - %@",responseDictionary);


}
}];
}
}];


[task resume];

}

View Controller

-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyReload:) name:@"ReloadNotification" object:nil];
}

在这里,我已经向 View Controller 传达了响应来自服务器的信息,并通过使用 NSNOTIFICATION 善意地在 View Controller 上反射(reflect)了响应。我实际上想通过委托(delegate)实现同样的事情。我是一名新程序员,正在尝试学习委托(delegate),但是无法理解这些概念,请用代码解释如何通过委托(delegate)完成相同的任务。提前致谢!

最佳答案

您可以通过 block 使用回调:

使用 block 声明的方法:

-(void)getResponse:(NSString *)url AndWithCallback:(void(^)(BOOL success, id responseObject))callback{
if(data != nil){
callback(YES,@"Your object");
}
else{
callback(NO,@"pass nil");
}
}

调用方法:

[self getResponse:@"" AndWithCallback:^(BOOL success, id responseObject) {
NSLog(@"%@",responseObject);
}];

关于ios - 如何实现委托(delegate)代替通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40177616/

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