Добавление данных JSON в UITableView - PullRequest
0 голосов
/ 26 марта 2012

Это пример метода getData в моем файле viewController.m

-(void) getData {
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]];

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];

// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
    NSString *text = [status objectForKey:@"text"];
    // You can retrieve individual values using objectForKey on the status NSDictionary
    // This will print the tweet and username to the console
    NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);

}
}

Что я хочу сделать, это взять [[status objectForKey:@"user"] и сделать его именем ячейки в табличном представлении. Какя бы пошел делать это?

РЕДАКТИРОВАТЬ: Хорошо, поэтому я получил его в строку, но теперь, когда я пытаюсь загрузить его, он вылетает, говоря [__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x6892b60'

, и это показывает поток прямо рядомcell.textLabel.text = [[statusArray objectAtIndex:indexPath.row] objectForKey:@"user"]; говоря Thread 1 SIGABRT

Ответы [ 2 ]

2 голосов
/ 26 марта 2012

В функции getData собрать все данные в массив.скажи это statusArray.Теперь, производный viewcontroller от UItableViewController.Сделайте член в этом классе типа NSArray и присвойте ему массив выше.Запишите ниже функции в класс контроллера.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [statusArray objectAtIndex:indexPath.row] objectForKey:@"user"];
    return cell;
}
0 голосов
/ 26 марта 2012

Реализация протокола UITableViewDataSource:

  • tableView:numberOfRowsInSection: - вернуть количество «статусов»
  • tableView:cellForRowAtIndexPath: - вернуть UITableViewCell, для которого textLabel.text установлен в ваш текст.

В документах Apple есть множество примеров, в том числе проект, который вы получаете, когда создаете новое приложение с помощью шаблона Xcode «Master-Detail App».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...