Разбор данных JSON для отображения в UItableview для iPhone - PullRequest
2 голосов
/ 02 сентября 2011

Я попытался перенести данные JSON на iPhone и подключил распечатал входящие данные JSON с помощью NSLOG. Я смог напечатать и протестировать конкретный узел. Я начал использовать цикл for для циклического перемещения по массиву подачи и отображенияэто в UItableview и не смог этого сделать.Перепробовал несколько вариантов, но не смог разобраться с этим. Пожалуйста, посмотрите на код и дайте мне знать, где и что я делаю неправильно. Я все еще изучаю кодирование на iPhone, так что любой вход будет очень полезным. Пожалуйста, найдите кодниже.

#import "RootViewController.h"
#import "SBJson.h"
#import "JSON.h"

@implementation RootViewController

NSMutableArray *listOfStates;
NSArray *exercises;
NSMutableData *responseData;


- (void)viewDidLoad
{
    //---initialize the array---
    listOfStates = [[NSMutableArray alloc] init];


    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/~xxxx/MyWorks/index.php?playerid=0"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self ];
    //NSURL *url = [NSURL URLWithString:@""]; 

    [super viewDidLoad];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse"); [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 valueForKey:@"feed"];

    NSLog(@"Here is the title of the feed: %@", [response valueForKey:@"video"]);


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

    [[self tableView] reloadData];

}




/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

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

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

    //create a cell
    UITableViewCell *cell = [[UITableViewCell alloc]
                             initWithStyle:UITableViewCellStyleDefault
                             reuseIdentifier:@"cell"];



    // fill it with contnets

    int ndx;
    for (ndx = 0; ndx <dictionary.count; ndx++) {
        NSDictionary *player = (NSDictionary *)[dictionary objectAtIndex:ndx];
        NSLog(@"Player: %@", [player valueForKey:@"player"]); 
    }
    NSString *cellValue = [player objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;
    // return it
    return cell;

}

1 Ответ

0 голосов
/ 02 сентября 2011

Трудно сказать, что не так, не зная, что происходит, но вот пара наблюдений.

  • Похоже, вы много раз анализировали свой ответ.Один раз в connectionDidFinishLoading для создания массива «упражнения», а затем снова каждый раз, когда ячейка визуализируется через tableView: cellForRowAtIndexPath :.Я бы предположил, что вы получаете все данные, которые вам нужны, когда вы впервые создаете массив упражнений из данных JSON.В этом случае tableView: cellForRowAtIndexPath: просто нужно получить объект из массива упражнений, а не работать с данными ответа.
  • Также здесь я не могу понять, что вы пытаетесь сделатьс циклом, в котором вы используете «player» - похоже, вы регистрируете информацию, но ничего не делаете с этими объектами игрока.В дополнение к тому, что они не используются, вы, похоже, теряете память с этими невыпущенными объектами.

На основании JSON, который вы добавили в своем комментарии, кажется, что массив упражнений будет содержать объекты NSDictionary.Это означает, что ваш код для установки текста в ячейке неверен.Вместо

NSString *cellValue = [response objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;

вы, вероятно, хотите что-то вроде

NSDictionary *exercise = [response objectAtIndex:indexPath.row];
cell.textLabel.text = [exercise valueForKey"player"];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...