未调用AFNetworking数据获取方法

时间:2012-06-12 17:14:17

标签: objective-c ios rest asynchronous afnetworking

我正在创建一个应用程序,在第一个视图中,用户可以选择登录或注册。在注册视图中有一个UITableViewCell,当点击该视频时,会将用户带到包含UITableViewUIPickerView的视图。 UITableView工作正常,但UIPickerView,它应该动态提取它应该使用网络电话显示的数据,但显示为完全空白。加入一些NSLog语句,我注意到模型中使用AFNetworking提取数据的方法永远不会被调用。我已经为UIPickerViewDelegateUIPickerViewDataSource方法发布了以下代码,以及应该在模型中提取数据的方法。提前谢谢。

UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row 
            forComponent:(NSInteger)component {
    return [[self.brain classChoicesForSignUp] objectAtIndex:row];
}

UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView 
numberOfRowsInComponent:(NSInteger)component {
    size_t numberOfRows = [self.brain classChoicesForSignUp].count;

    NSLog(@"Number of Rows: %@", [[NSNumber numberWithFloat:numberOfRows] stringValue]);

    return numberOfRows;
}

SignUpPickerBrain.m

#import "SignUpPickerBrain.h"
#import "AFJSONRequestOperation.h"

@implementation SignUpPickerBrain

#pragma mark - Picker Data

- (NSArray *)classChoicesForSignUp {
    NSLog(@"Class choices method called");
    // Note that in my code, the actual URL is present here.
    NSURL *url = [NSURL URLWithString:@"the URL"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"Success!");
        NSLog([JSON description]);
    } failure:nil];

    [operation start];
    [operation waitUntilFinished];
    NSLog([operation responseJSON]);
    return [operation responseJSON];
}

@end

1 个答案:

答案 0 :(得分:0)

此代码示例中有许多反模式。我强烈建议您不要采用当前的方法,并考虑以下几点:

  • 联网异步,即不要使用[operation waitUntilFinished];。无论何时创建发出网络请求的方法,都要给它一个块参数,一旦结果出来就可以用作回调。
  • 将结果存储在控制器中的数组属性中,然后使用它来驱动代理和数据源。在您当前的方法中,每次显示一行时都会进行网络请求(!)。因此,初始化为空数组,一旦将新结果设置为该属性,重新加载数据源。一个异步请求。容易。
  • 摆脱SignUpPickerBrain。要么使用正确的模型,要么只在Controller中进行调用。示例iOS项目有一些很好的模式可供使用。
  • 使用AFHTTPClient。如果您正在与特定的Web服务进行交互,那么使用AFHTTPClient子类来处理所有这些请求会非常有用。