尝试在iOS中使用Singleton模式重构网络方法

尝试在iOS中使用Singleton模式重构网络方法,第1张

概述我的应用程序中有以下方法,它使用NSURLSession从 JSON格式的Web服务中提取电影数据: - (void) downloadMovieData { //this is just a visual cue to show that processing is being done [[UIApplication sharedApplication] setNetwork 我的应用程序中有以下方法,它使用NSURLSession从 JSON格式的Web服务中提取电影数据:

- (voID) downloadMovIEData {    //this is just a visual cue to show that processing is being done    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];    //creating the request    NSURL *url = [NSURL URLWithString:kMovIEURL];    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //creating the session    self.config = [NSURLSessionConfiguration defaultSessionConfiguration];    self.session = [NSURLSession sessionWithConfiguration:self.config];    //the object that makes the call to the web service using the request and the session,and returns a response or an error    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {        //At this point a response has been received,so we can turn the indicator off        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];        //I am casting the response to an NShttpURLResponse so I can check the status code of the response        NShttpURLResponse *httpResponse = (NShttpURLResponse *)response;        //a status code of 200 means a successful connection with the web service        if (httpResponse.statusCode == 200) {            dispatch_async(dispatch_get_main_queue(),^{                NSLog(@"Success!");                //I send the data that was received from the response to the method so that the JsON data is extracted                [self populateArray:data];            });        } else {            Nsstring *result = [[Nsstring alloc] initWithData:data enCoding:NSUTF8StringEnCoding];            NSLog(@"Received http %ld: %@",(long)httpResponse.statusCode,result);        }    }];    [task resume];}- (voID) populateArray: (NSData *)data {    NSError *JsonError;    NSDictionary *response =[NSJsONSerialization JsONObjectWithData:data options:NSJsONReadingallowFragments error:&JsonError];    if (response) {        self.movIEObjects = response[@"movIEs"];        NSLog(@"The movIE objects are: %@",self.movIEObjects);        [self.tableVIEw reloadData];    } else {        NSLog(@"ERROR: %@",JsonError);    }}

上面的代码工作正常.没有问题.但是,我现在要做的是重构我的代码,以便在包含我的UItableVIEw委托方法的类中包含所有网络代码,我想将代码移动到一个单独的类中,该类使用Singleton方法更好地分离代码我有以下框架代码,如下所示:

#import "Networker.h"@implementation Networker+ (NSURLSession *)dataSession {    static NSURLSession *session = nil;    static dispatch_once_t oncetoken;    dispatch_once(&oncetoken,^{        session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];    });    return session;}+ (voID)fetchContentsOfURL:(NSURL *)url completion:(voID (^)(NSData *data,NSError *error)) completionHandler {    NSURLSessionDataTask *dataTask = [[self dataSession] dataTaskWithURL:url                      completionHandler: ^(NSData *data,NSError *error) {         if (completionHandler == nil) return;         if (error) {             completionHandler(nil,error);             return;         }         completionHandler(data,nil);     }];    [dataTask resume];}

我完全理解Singleton类没有问题.这不是问题.我的问题是了解如何理解此方法的“完成处理程序”部分:

+ (voID)fetchContentsOfURL:(NSURL *)url completion:(voID (^)(NSData *data,NSError *error)) completionHandler {}

我想做的是将我在方法中的代码“downloadMovIEData”移动到“fetchContentsOfURL”中,然后返回一个NSData对象,然后我可以使用它来填充我的调用类中的UItableVIEw.但是,在这样做的过程中,我想确保我理解这个新方法的“completionHandler”部分发生了什么.我怎样才能做到这一点?

解决方法 你不能移动它以便它返回,因为它是异步的.从技术上讲你可以,但你在等待时阻止主线程这是坏事.

相反,您只需用对单例的调用替换当前代码,在完成块中调用其他方法来处理数据.

有几点需要注意:

>在调用某人完成块之前调出main中的main是个好主意,这样你就不需要函数的所有用户记住这样做了>它不需要是单例,您可以在每次需要时实例化类的副本或使用依赖注入,这两者通常都提供更好的体系结构

总结

以上是内存溢出为你收集整理的尝试在iOS中使用Singleton模式重构网络方法全部内容,希望文章能够帮你解决尝试在iOS中使用Singleton模式重构网络方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1028441.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存