发送POST后重新加载UITableView

时间:2012-08-02 14:00:39

标签: objective-c ios

我试图在发布一些数据后重新加载我的UITableView。这是代码:

-(IBAction)carregaLista{

NSError *err = nil;
NSURLResponse *response = nil;

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

NSString *theURL = [NSString stringWithFormat:@"http://localhost/tests/json/"];
NSURL *URL = [NSURL URLWithString:theURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];

NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

resultsDictionary = [[NSDictionary alloc] init];

resultsDictionary = [jsonData objectFromJSONData];
//NSLog(@"my dictionary = %@", resultsDictionary);


self.billsArray = [[NSArray alloc] init];
self.billsArray = [resultsDictionary objectForKey:@"bills"];

// Add values to its array

double sum = [[self.billsArray valueForKeyPath:@"@sum.value"] doubleValue];

NSString *totalString = [NSString stringWithFormat:@"%0.2f", sum];
self.total.text = totalString;

// Custom table cell

tabela.rowHeight = 100;
[self.tabela reloadData];
NSLog(@"Chamou carregaLista");

}

然后,在AddViewController中:

-(IBAction)enviaCadastro:(id)sender{

NSLog(@"Nome: %@, Valor: %@", self.nome.text, self.valor.text);

NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/tests/json/add.php"]];
[request setHTTPMethod:@"POST"];

NSString *post =[[NSString alloc] initWithFormat:@"nome=%@&valor=%@", self.nome.text, self.valor.text];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

float respCode = [responseString floatValue];
if(respCode < 400) {
    [self dismissModalViewControllerAnimated:YES];
    ViewController *firstView = [[ViewController alloc] init];
    [firstView carregaLista];
}
else {
    NSLog(@"NAO DEU CERTO");
}


}

如何使用新添加的数据重新加载表格?

感谢。

3 个答案:

答案 0 :(得分:1)

此...

ViewController *firstView = [[ViewController alloc] init];

...创建一个视图控制器,它与您已有的任何实例不同,并且不是具有在屏幕上可见的视图的实例。您可能正在更新其数据属性并期望更新显示在视图中。我相信您需要在已经属于您应用的carregaLista上致电ViewController

答案 1 :(得分:0)

我无法确定这是否是相同的情况,但我遇到了与UIPickerView -reloadAllComponents方法类似的问题。我注意到如果该行离开屏幕然后又回来更新了。我所期望的以前的方法做的那种。

我可以更新的方法是使用方法-removeAllObjects删除我的NSMutableArray中的内容,然后立即调用-addObject:然后调用-reloadAllComponents。我有一种感觉,你可以做类似的事情,并得到你需要的结果。

答案 2 :(得分:0)

想通了。我在carregaLista内拨打viewDidLoad。只要把viewWillAppear放进去就行了。感谢大家。