如何代替通知实施委托

时间:2016-10-21 13:13:15

标签: ios objective-c iphone delegates

## 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];
}

在这里,我已经向viewcontroller传达了响应来自服务器,并通过使用NSNOTIFICATION在视图控制器上反映出响应。我实际上想通过委托实现同样的事情。我是一个新的程序员,并试图学习代表但是不能理解这些概念,请用代码解释如何通过代表完成相同的任务。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过块使用回调:

使用块声明的方法:

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