2010-06-03 111 views
4

我想用json结果中的数据填充UITableView。我可以得到它从plist数组加载没有问题,我甚至可以看到我的JSON。我遇到的问题是UITableView永远不会看到json结果。请耐心等待,因为这是我第一次使用Objective-C。从JSON填充UITableView

在我的.h文件

@interface TableViewViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { 
    NSArray *exercises; 
    NSMutableData *responseData; 

} 

在我的.m文件

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return exercises.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    //create a cell 
    UITableViewCell *cell = [[UITableViewCell alloc] 
    initWithStyle:UITableViewCellStyleDefault 
    reuseIdentifier:@"cell"]; 

    // fill it with contnets 
    cell.textLabel.text = [exercises objectAtIndex:indexPath.row]; 
    // return it 
    return cell; 
} 


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad {  
    responseData = [[NSMutableData data] retain]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://url_to_json"]]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self ]; 


    // load from plist 
    //NSString *myfile = [[NSBundle mainBundle] pathForResource:@"exercise" ofType:@"plist"]; 
    //exercises = [[NSArray alloc] initWithContentsOfFile:myfile]; 
    [super viewDidLoad]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    [responseData setLength:0]; 
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    NSLog(@"Connection failed: %@", [error description]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    [connection release]; 

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
    [responseData release]; 

    NSDictionary *dictionary = [responseString JSONValue]; 
    NSArray *response = [dictionary objectForKey:@"response"]; 

    exercises = [[NSArray alloc] initWithArray:response]; 
} 

回答

14

你需要告诉你的表视图重装。尝试添加:

[tableView reloadData]; 

你-connectionDidFinishLoading方法结束。

+0

我得到的错误,说tableView不delcared? – mcgrailm 2010-06-03 18:47:09

+0

好的。你的视图控制器是一个UITableViewController还是一个UIViewController?你将需要一个到你的UITableView的插座。如果你的视图控制器是一个UITableViewController,将上面的代码改为[[self tableView] reloadData];否则,在头文件中声明一个UITableView IBOutlet并将其命名为tableView并将其连接到Interface Builder中。然后代码应该工作。 – 2010-06-03 20:52:30

+0

好吧,得到这部分工作感谢您的帮助 – mcgrailm 2010-06-03 20:56:28

1

使用

[self.tableView reloadData]; 
0

你可能需要在你的connectionDidFinishLoading方法的末尾添加下面的代码行:

[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 

这将刷新UITableView的主线程上,因为connectionDidFinishLoading正在在不同的线程上执行。