我从数据库中获取一些数据并将其保存到我创建的对象(称为“ManejadorMateria”)中。然后,我希望能够在下一个视图控制器的表格视图中显示这些数据;问题是请求操作需要在前一个视图控制器的prepareforsegue方法上进行,并且在我需要的数据保存在ManejadorMateria对象之前调用表视图的cellForRowAtIndexPath方法。在应用程序的下一次操作之前完成请求操作
在触发方法cellForRowAtIndexPath之前,我能做些什么来获取数据?
发出请求到数据库中,我使用这个代码:
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion (JSONResponseBlock)completionBlock
{
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:@"POST"
path:kAPIPath
parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
}];
[operation start];
}
为了得到我所需要的数据,我用这个代码:
- (void)cargarMateriasDeCarrera:(NSString *)carrera{
Materias = [[NSMutableArray alloc] init];
Manejador = [[ManejadorMateria alloc] init];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"getMaterias", @"command",
carrera, @"carrera",
nil];
[[API sharedInstance] commandWithParams:params
onCompletion:^(NSDictionary *json) {
//handle the response
NSDictionary* res = [json objectForKey:@"result"];
Materia *materiafuente = [[Materia alloc]init];
for (id r in res) {
materiafuente.Nombre = [NSString stringWithFormat:@"%@",[r objectForKey:@"nombre"]];
materiafuente.Codigo = [NSString stringWithFormat:@"%@",[r objectForKey:@"codigo"]];
materiafuente.Descripcion = [NSString stringWithFormat:@"%@",[r objectForKey:@"descripcion"]];
materiafuente.GradoDificultad = [r objectForKey:@"grado"];
[Materias addObject:materiafuente];
}
[Manejador setMasterMateriasTodas:Materias];
}];
}
在prepareforsegue
最后同样的视图控制器上,我有:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
usuario.Carrera = [carreras objectAtIndex:self.tableView.indexPathForSelectedRow.row];
TablaMateriasViewController3 *tbvc3 = [segue destinationViewController];
tbvc3.usuario = usuario;
NSString *command = @"registraCarrera";
NSMutableDictionary *params =[NSMutableDictionary dictionaryWithObjectsAndKeys:
command, @"command",
usuario.Carnet, @"carnet",
usuario.Carrera, @"carrera",
nil];
[[API sharedInstance] commandWithParams:params
onCompletion:^(NSDictionary *json) {
}];
[self cargarMateriasDeCarrera:usuario.Carrera];
tbvc3.Manejador = Manejador;
}
我期待着一些线程,而不是回顾这种方法,因为我不知道我正在获取的数据的大小 – Sabaspro
当你异步下载(就像你在做的那样)你*是*使用线程。 – matt
非常感谢马特,但是当操作等待完成时,我怎么能让主线程进入休眠状态 – Sabaspro