在解除模态视图控制器后未调用Delegate方法

时间:2013-11-17 21:40:34

标签: ios objective-c json nsurlrequest nsurlsession

我正在使用NSURLSessionDataTask从我的JsonClient类的url中检索JSON,这个类有一个委托协议,可以在json任务完成时通知。

JsonClient.h

#import <Foundation/Foundation.h>

@protocol JsonDelegate <NSObject>
- (void)jsonFetchComplete;
@end

@interface JsonClient : NSObject

@property (weak,nonatomic) id <JsonDelegate> delegate;

- (void)fetchJsonData;

@end

JsonClient.m

#import "JsonClient.h"

@implementation JsonClient

- (void)fetchJsonData {

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    NSString *urlString = @"http://api.kivaws.org/v1/loans/search.json?status=fundraising";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //urlString = [urlString stringByAppendingString:@".json"];

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:10];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {

                                                    NSLog(@"error: %@",error.localizedDescription);

                                                    dispatch_sync(dispatch_get_main_queue(), ^{
                                                        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

                                                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR"
                                                                                                        message:error.localizedDescription
                                                                                                       delegate:self
                                                                                              cancelButtonTitle:@"Cancel"
                                                                                              otherButtonTitles:nil];
                                                        [alert show];
                                                    });

                                                } else {
                                                    NSLog(@"got data");

                                                    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

                                                    NSError *jsonerror = nil;

                                                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonerror];

                                                    dispatch_sync(dispatch_get_main_queue(), ^{
                                                        NSLog(@"json is \n %@",dict);
                                                        [self.delegate jsonFetchComplete];
                                                        NSLog(@"done");
                                                    });
                                                }
                                            }];
    [task resume];
}

@end

获取json工作正常。但由于某种原因,委托方法没有在我的第一个视图控制器中调用。 ViewControllerViewController2提供了模态segue。 ViewController2中的按钮在点按时获取json,然后将其关闭回第一个ViewController

ViewController.m

#import "ViewController.h"
#import "JsonClient.h"

@interface ViewController () <JsonDelegate>
@property (weak,nonatomic) IBOutlet UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.label.text = @"Loaded VC";
}

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"view will appear");

    JsonClient *jc = [[JsonClient alloc] init];
    jc.delegate = self;
}

// delegate method from JsonClient
- (void)jsonFetchComplete {
    NSLog(@"fetch complete");
    self.label.text = @"Completed!";
}

- (IBAction)toHome:(UIStoryboardSegue *)segue {
    // unwind segue
}

@end

ViewController2.m

#import "ViewController2.h"
#import "JsonClient.h"
#import "ViewController.h"

@interface ViewController2 ()

@end

@implementation ViewController2

- (IBAction)getJsonData:(id)sender {

    JsonClient *jsonClient = [[JsonClient alloc] init];
    [jsonClient fetchJsonData];

    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

为什么第一个视图控制器ViewController中的委托方法没有被调用?

1 个答案:

答案 0 :(得分:1)

除非JsonClient是单身人士,并且您没有告诉我们,否则您要创建JsonClient的两个实例,viewWillAppear方法ViewController中的一个getJsonData的{​​{1}}方法中的另一个。

这两个实例分别跟踪他们的代表,而您只设置其中一个。第二个,即单击ViewController2中的按钮时调用的那个,从未设置其委托,因此默认为ViewController2,发送给nil的消息不执行任何操作。 / p>

您需要以下内容:

nil