UITableView сделать 1 раздел на каждый день из NSMutableArray - PullRequest
2 голосов
/ 20 сентября 2011

Я застрял с этой проблемой, у меня есть UITableView, и я заполняю его данными из NSMutableArray.Массив имеет следующую структуру:

<array>
<dict>
    <key>Date</key>
    <string>2011.18.09 04:17 PM</string>
    <key>Value</key>
    <string>58.00</string>
</dict>
<dict>
    <string>2011.15.09 04:21 PM</string>
    <key>Value</key>
    <string>0.00</string>
</dict>
</array>

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

Рабочий код:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
NSMutableArray *test = [d valueForKey:@"Date"];
NSString *g = [[NSString alloc] init];
NSString *s = [[NSString alloc] init];
c = 0;
    for (g in test) {
        s = [g substringToIndex:[g length]-9];
        if (![s isEqualToString:sf]) {
            c = c+1;
            [dates addObject:s];
        }
        sf = [g substringToIndex:[g length]-9];
    }
return c;

этот код считает различные даты и создает массив с именами разделов.Может ли кто-нибудь помочь мне с определением количества строк (путем подсчета количества объектов для каждого дня) и путем задания правильного значения для строк в методе «CellForRowAtIndexPath».

Ответы [ 2 ]

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

Хорошо, я наконец нашел решение. Это на самом деле довольно легко понять. Чтобы вернуть номера разделов, мне нужно выяснить, сколько разных дат в массиве. Для количества строк мне нужно знать, сколько значений существует на каждый день. вот что я сделал:

Ряды:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
    NSMutableArray *d = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSArray *jes = [[NSArray alloc] init];
    count = [[NSMutableArray alloc] init];
    NSString *before = [[NSString alloc] init];
    NSString *after = [[NSString alloc] init];
    jes = [d valueForKey:@"Date"];
    int ja = -1;
    for (int i = 1; i<=[jes count];i++) {
        ja = ja+1;
        before = [jes objectAtIndex:ja];
        if (![before isEqualToString:after]) {
            NSCountedSet *ca = [[NSCountedSet alloc] initWithArray:jes];
            int f = [ca countForObject:before];
            [count addObject:[NSString stringWithFormat:@"%i",f]];
        }
        after = before;
    }
    return [[count objectAtIndex:section] intValue];
}

Разделы:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
    NSMutableArray *d = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSArray *jes = [[NSArray alloc] init];
    count = [[NSMutableArray alloc] init];
    NSString *before = [[NSString alloc] init];
    NSString *after = [[NSString alloc] init];
    jes = [d valueForKey:@"Date"];
    int ja = -1;
    for (int i = 1; i<=[jes count];i++) {
        ja = ja+1;
        before = [jes objectAtIndex:ja];
        if (![before isEqualToString:after]) {
            NSCountedSet *ca = [[NSCountedSet alloc] initWithArray:jes];
            int f = [ca countForObject:before];
            [count addObject:[NSString stringWithFormat:@"%i",f]];
        }
        after = before;
    }
    return [count count];
}

Титулы:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
    NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
    NSMutableArray *test = [d valueForKey:@"Date"];
    NSString *g = [[NSString alloc] init];
    NSString *s = [[NSString alloc] init];
    NSString *sf = [[NSString alloc] init];
    dates = [[NSMutableArray alloc] init];
    c = 0;
    for (g in test) {
        s = [g substringToIndex:[g length]-9];
        if (![s isEqualToString:sf]) {
            c = c+1;
            [dates addObject:s];
        }
        sf = [g substringToIndex:[g length]-9];
    }
    return [dates objectAtIndex:section];
}
0 голосов
/ 20 сентября 2011

Не alloc и init g и s в приведенном выше коде, это не является необходимым и вызывает утечку памяти.

Я бы прошел через ваш массив и создал бы второй массив, содержащийсловари.Каждый словарь будет содержать два объекта, одну дату и один массив.Массив будет содержать все значения, применимые к каждой дате.

Используя эту технику, счетчик основного массива будет количеством разделов, а количество строк в разделе - счетчиком массива в словаре.Значением для каждой строки будет объект с соответствующим индексом для раздела (основной массив) и строки (внутренний массив).

Вот немного проверенный код, который может делать то, что вы хотите:

    NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:@"test.plist"];
    [array sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:YES]]];

    NSMutableArray *datesList = [[NSMutableArray alloc] init ];
    NSString *previousDate = @"";
    NSMutableArray *currentDateValues;

    for (NSDictionary * dict in array)
    {
        if ([[[dict objectForKey:@"Date"] substringToIndex:10] isEqualToString:previousDate])
        {
            // This is another entry from the same date
            [currentDateValues addObject:[dict objectForKey:@"Value"]];
        }
        else
        {
            // We haven't seen this date before
            previousDate = [[dict objectForKey:@"Date"] substringToIndex:10];
            currentDateValues = [NSMutableArray array];
            [currentDateValues addObject:[dict objectForKey:@"Value"]];
            NSDictionary *newDate = [NSDictionary dictionaryWithObjectsAndKeys:previousDate,@"Date",currentDateValues,@"Values", nil];
            [datesList addObject:newDate];
        }
    }

Это должно оставить вас с одним массивом datesList, который содержит словарь для каждой даты имассив всех значений для каждой даты.

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