How to implement delegate in place of notification

╄→尐↘猪︶ㄣ 提交于 2019-12-25 04:46:19

问题


## NetworkClass

-(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];

}

ViewController

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

Here I have communicated to the viewcontroller that response has come from server and kindly reflect the response on view controller by using NSNOTIFICATION .I actually want to implement the same thing through delegates .I am a new programmer and trying to learn delegates but not able to understand the concepts ,kindly explain with code that how the same task can be done through delegates.Thanks in advance!


回答1:


You can do using callback through blocks:

Declared method using block :

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

Invoke Method :

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


来源:https://stackoverflow.com/questions/40177616/how-to-implement-delegate-in-place-of-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!