从json填充UITableView

mcg*_*ilm 4 iphone objective-c ipad

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

在我的.h文件中

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

}
Run Code Online (Sandbox Code Playgroud)

在我的.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];
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ong 14

您需要告诉您的表视图重新加载.尝试添加:

[tableView reloadData];
Run Code Online (Sandbox Code Playgroud)

在你的-connectionDidFinishLoading方法的最后.