我正在使用AFNetworking库从服务器中提取一个JSON提要来填充UIPickerView,但是我很难用异步的方式来处理事情。@property classChoices是一个用于填充UIPickerView的NSArray,因此web调用只执行一次。但是,由于该块在返回实例变量时尚未完成,因此getter返回零,并且它最终会导致我的程序稍后崩溃。如果能帮助解决这个问题,我们将不胜感激。如果你需要更多的信息,请告诉我。
PickerViewController.m classChoices Getter
- (NSArray *)classChoices {
if (!_classChoices) {
// self.brain here refers to code for the SignUpPickerBrain below
[self.brain classChoicesForSignUpWithBlock:^(NSArray *classChoices) {
_classChoices = classChoices;
}];
}
return _classChoices;
}SignUpPickerBrain.m
- (NSArray *)classChoicesForSignUpWithBlock:(void (^)(NSArray *classChoices))block {
[[UloopAPIClient sharedClient] getPath:@"mobClass.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseJSON) {
NSLog(responseJSON);
if (block) {
block(responseJSON);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
if (block) {
block(nil);
}
}];
}发布于 2012-06-15 17:30:17
您需要一个类似于PickerViewController中的方法,该方法在下载数组后返回数组。返回回调后,您可以继续使用代码:
- (void)classChoices:(void (^) (NSArray * classChoices)) _callback {
if (!self.classChoices) {
// self.brain here refers to code for the SignUpPickerBrain below
[self.brain classChoicesForSignUpWithBlock:^(NSArray *classChoices) {
_callback(classChoices);
}];
}
}
// call the method
- (void) viewDidLoad {
[super viewDidLoad];
[self classChoices:^(NSArray * updatedChoices) {
self.classChoices = updatedChoices;
[self.pickerView reloadAllComponents];
}];
}https://stackoverflow.com/questions/11055468
复制相似问题