2010-06-03 2 views
4

Я пытаюсь заполнить UITableView данными из результата json. Я могу получить его для загрузки с plist массив без проблем, и я даже могу увидеть мой json. Проблема, с которой я сталкиваюсь, заключается в том, что UITableView никогда не увидит результаты json. пожалуйста, несите меня, поскольку это мой первый раз с Objective-C.заполнять UITableView от json

В моем файле .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]; 

в конец вашего -соединенияDidFinishLoading method.

+0

Я получаю сообщение о том, что tableView не delcared? – mcgrailm

+0

Хорошо. Является ли ваш контроллер просмотра UITableViewController или просто UIViewController? Вам понадобится выход в UITableView. Если ваш контроллер просмотра является UITableViewController, измените приведенный выше код на [[self tableView] reloadData]; В противном случае объявите UITableView IBOutlet в своем заголовочном файле и назовите его tableView и подключите его в Interface Builder. Тогда код должен работать. –

+0

ok получил эту часть работы за вашу помощь – mcgrailm

0

Вы можете добавить следующую строку кода в конце вашего метода connectionDidFinishLoading:

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

Это обновит UITableView в главном потоке, поскольку connectionDidFinishLoading в настоящее время выполняются в другом потоке.

Смежные вопросы