我正在创建一个应用程序,在第一个视图中,用户可以选择登录或注册。在注册视图中有一个UITableViewCell
,当点击该视频时,会将用户带到包含UITableView
和UIPickerView
的视图。 UITableView
工作正常,但UIPickerView
,它应该动态提取它应该使用网络电话显示的数据,但显示为完全空白。加入一些NSLog
语句,我注意到模型中使用AFNetworking
提取数据的方法永远不会被调用。我已经为UIPickerViewDelegate
和UIPickerViewDataSource
方法发布了以下代码,以及应该在模型中提取数据的方法。提前谢谢。
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
答案 0 :(得分:0)
此代码示例中有许多反模式。我强烈建议您不要采用当前的方法,并考虑以下几点:
[operation waitUntilFinished];
。无论何时创建发出网络请求的方法,都要给它一个块参数,一旦结果出来就可以用作回调。SignUpPickerBrain
。要么使用正确的模型,要么只在Controller中进行调用。示例iOS项目有一些很好的模式可供使用。AFHTTPClient
。如果您正在与特定的Web服务进行交互,那么使用AFHTTPClient
子类来处理所有这些请求会非常有用。