0

我正在创建一个应用程序,在第一个视图中,用户可以选择登录或注册。在注册视图中是 a UITableViewCell,当单击它时,会将用户带到包含 aUITableView和 a的视图UIPickerViewUITableView工作正常,但是UIPickerView应该动态提取它应该使用网络调用显示的数据的 正在显示,但看起来完全空白。加上几句NSLog话,我注意到模型中使用拉取数据的方法AFNetworking永远不会被调用。我已经为UIPickerViewDelegateandUIPickerViewDataSource方法发布了下面的代码,以及应该在模型中提取数据的方法。提前致谢。

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

注册PickerBrain.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
4

1 回答 1

0

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

  • 做网络异步,即不要使用[operation waitUntilFinished];. 每当你创建一个发出网络请求的方法时,给它一个块参数,一旦结果进来就可以用作回调。
  • 将您的结果存储在控制器等的数组属性中,并使用它来驱动您的委托和数据源。在您当前的方法中,您将在每次显示一行时执行一个网络请求(!)。因此,相反,初始化为一个空数组,一旦新结果设置为该属性,重新加载数据源。一个异步请求。简单的。
  • 摆脱SignUpPickerBrain. 要么使用合适的模型,要么只在 Controller 中自己调用。示例 iOS 项目有一些很好的模式可供遵循。
  • 使用AFHTTPClient. 如果您正在与特定的 Web 服务进行交互,那么拥有一个AFHTTPClient子类来处理所有这些请求会非常有用。
于 2012-06-13T15:16:20.403 回答