Добавление значений в ячейку из файла JSON - предоставленный код - PullRequest
0 голосов
/ 31 января 2012

У меня есть файл JSON, и мне нужно извлечь значения из него и отобразить в моем табличном представлении.Все работает нормально.

{
    "1": {
        "name": "Jemmy",
        "birthday": "1994-11-23"
    },
    "2": {
        "name": "Sarah",
        "birthday": "1994-04-12"
    },
    "3": {
        "name": "Deb",
        "birthday": "1994-11-23"
    },
    "4": {
        "name": "Sam",
        "birthday": "1994-11-23"
    }
} 

Когда я отображаю значения, он не отображается в порядке 1,2,3,4, как указано в записях.Это просто отображается случайным образом.Я включил свой код ниже, мне нужно его изменить, чтобы я мог отображать содержимое в порядке, указанном выше.Может кто-нибудь помочь, пожалуйста?

- (void)requestSuccessfullyCompleted:(ASIHTTPRequest *)request{
                NSString *responseString = [request responseString];
                SBJsonParser *parser = [SBJsonParser new];               
                id content = [responseString JSONValue];
                if(!content){       
                    return;
                }
                NSDictionary *personDictionary = content;
                NSMutableArray *personMutableArray = [[NSMutableArray alloc] init];
                for (NSDictionary *childDictionary in personDictionary.allValues)
                {
                    Deal *deal = [[Deal alloc] init];            
                    deal.name=[childDictionary objectForKey:@"name"];
                    deal.dob=[childDictionary objectForKey:@"birthday"];
                    [personMutableArray addObject:deal];
                }        
                self.personArray = [NSArray arrayWithArray:personMutableArray];    
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {        
            Person *person = [self.personArray objectAtIndex:indexPath.row];        
            cell = [[Cell alloc] initWithStyle:UITableViewCellStyleDefault 
                               reuseIdentifier:CellIdentifier];
            cell.namelabel.text=person.name;   
            cell.doblabel.text=person.dob;  
        }
        return cell;
    }

Ответы [ 3 ]

1 голос
/ 31 января 2012

Вы неправильно используете свою клетку.Если ячейка используется повторно, вы не можете ее настроить.

Ваш cellForRowAtIndexPath: должен быть таким:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {        
        cell = [[Cell alloc] initWithStyle:UITableViewCellStyleDefault 
                           reuseIdentifier:CellIdentifier];
    }
    Person *person = [self.personArray objectAtIndex:indexPath.row];        
    cell.namelabel.text=person.name;   
    cell.doblabel.text=person.dob;  
    return cell;
}

Обратите внимание, что это правильный код ARC, но в пре-ARCнеобходимо добавить autorelease в конец строки [Cell alloc].

0 голосов
/ 31 января 2012

Данные из JSON хранятся в словаре, в котором не хранятся упорядоченные данные. Вы должны получить эти данные по порядку в массиве или отсортировать массив после слов.

Вы можете отсортировать массив, в котором вы храните данные словаря, если вы хотите отсортировать их в алфавитном порядке по имени, вы можете сделать это:

self.personArray = [personMutableArray sortedArrayUsingSelector:@selector(compare:)];


- (NSComparisonResult)compare:(Deal *)dealObject {
    return [self.name compare:dealObject.name];
}

Если вы хотите, чтобы данные были представлены в виде JSON, вы должны сделать что-то вроде этого:

for (int i = 1; i < [personDictionary.allValues count]; i++)
{
    NSDictionary *childDictionary = [[personDictionary objectForKey:[NSString stringWithFormat:@"%d", i]];

    Deal *deal = [[Deal alloc] init];            
    deal.name=[childDictionary objectForKey:@"name"];
    deal.dob=[childDictionary objectForKey:@"birthday"];
    [personMutableArray addObject:deal];
}        
0 голосов
/ 31 января 2012

Попробуйте и исправьте cellForRowAtIndexPath: для повторно используемых ячеек

- (void)requestSuccessfullyCompleted:(ASIHTTPRequest *)request{
                NSString *responseString = [request responseString];
                SBJsonParser *parser = [SBJsonParser new];               
                id content = [responseString JSONValue];
                if(!content){       
                    return;
                }
                NSDictionary *personDictionary = content;
                NSMutableArray *personMutableArray = [[NSMutableArray alloc] init];
                NSArray *array = [personDictionary allKeys];
                NSArray * sortedArray = [array sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

                for (NSString *str in sortedArray)
                {
                    NSDictionary *childDictionary = [personDictionary objectForKey:str];
                    Deal *deal = [[Deal alloc] init];            
                    deal.name=[childDictionary objectForKey:@"name"];
                    deal.dob=[childDictionary objectForKey:@"birthday"];
                    [personMutableArray addObject:deal];
                }        
                self.personArray = [NSArray arrayWithArray:personMutableArray];    
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...