我正在从我的数据库中获取一些数据并将其保存到我创建的对象中(称为“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;
}