Вложенный NSArray в UITableView - PullRequest
       4

Вложенный NSArray в UITableView

0 голосов
/ 14 декабря 2010

Я искал повсюду это, но я не могу найти точный ответ ... у всех есть небольшие различия.

В любом случае, я вызываю страницу json, которая возвращает следующее (из NSLog):

{
    messages =         {
        1 =             {
            Body = "This is the body of message 1";
            Title = "Message 1";
        };
        2 =             {
            Body = "This is the body of message 2";
            Title = "Message 2";
        };
    };
}

Затем я сохраняю данные в NSDictionary (называемый messageArray). (массив является NSMutableArray)

тогда я делаю:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    NSLog(@"the message array = %@",messages );

    //this fails
    cell.textLabel.text = [messages objectAtIndex:indexPath.row];

return cell;

возвращенный NSLog (поэтому я предполагаю, что мой массив json работает правильно):

the message array = {
1 =     {
    Body = "This is the body of message 1";
    Title = "Message 1";
};
2 =     {
    Body = "This is the body of message 2";
    Title = "Message 2";
};

}

Я понимаю, что не правильно маркирую textlabels.text, но я не уверен, как выполнить цикл по массиву "messages", чтобы отобразить все значения "Title" из массива, чтобы отобразить на моем UITableView список.

Я уверен, что мне не хватает чего-то такого простого ... но это ускользало от меня до сих пор. Любые ссылки приветствуются ... я буду продолжать искать себя ....

Ответы [ 4 ]

1 голос
/ 14 декабря 2010
NSArray *messages = [dictionary objectForKey:@"messages"];

зачем нужна эта строка, если вы получаете свой словарь здесь

NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

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

тогда просто

cell.textLabel.text = [dictionary valueForKey:@"Title"];
cell.detailTextLabel.text= [dictionary valueForKey:@"Body"];
0 голосов
/ 14 декабря 2010
cell.textLabel.text = [[messages objectAtIndex:indexPath.row] objectForKey:@"Title"];
cell.detailTextLabel.detailLabel = [[messages objectAtIndex:indexPath.row] objectForKey:@"Body"];
0 голосов
/ 14 декабря 2010

у меня "полу" разобрали проблему.Я удалил индексы из данных json, теперь они выглядят так:

messages =     (
            {
        Body = "This is the body of message 1";
        Title = "Message 1";
    },
            {
        Body = "This is the body of message 2";
        Title = "Message 2";
    }
);

И я использовал это для заполнения таблицы:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    //put rowsarray into dictionary
    NSDictionary *dictionary = [messageArray objectAtIndex:indexPath.section];

    NSLog(@"dictionary = %@", dictionary );

    //new dictionary into array
    NSArray *messages = [dictionary objectForKey:@"messages"];

    //NSArray *message=[[messages allKeys] sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"array messages = %@", messages );

    cell.textLabel.text = [[messages objectAtIndex:indexPath.row] objectForKey:@"Title"]; 

    return cell;
}

Надеюсь, это кому-нибудь поможет.

0 голосов
/ 14 декабря 2010

Этот звонок

cell.textLabel.text = [messages objectAtIndex:indexPath.row];

похоже, что он возвращает словарь, а вы пытаетесь вставить его в тестовое поле. Я бы подтвердил, что это сначала словарь, что-то вроде:

NSLog(@"%@",  [messages objectAtIndex:indexPath.row])

Если это не строка, это может быть вашей проблемой.

Чтобы получить желаемую строку, вы можете сделать что-то вроде:

 [[messages objectAtIndex:indexPath.row] valueForKey:@"Title"]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...