Как альтернативно вызвать numberOfRowsInSection и cellForRowAtIndexPath - PullRequest
1 голос
/ 16 августа 2011

Я работаю над приложением, в котором данные отображаются из серверной части в таблицу. Проблема в том, что когда таблица загружается, она получает все данные, но отображает только последнюю запись базы данных в каждой строке. Предположим, что последний раздел имеет 3 строки, тогда он отображает только 3, что 3 строки данных в каждом разделе. Даже если в некоторых разделах строк 9, остальные строки отображаются пустыми.

Я обнаружил, что через точки останова таблица сначала берет все данные из базы данных, а затем читает cellForRowAtIndexPath. Поскольку в моей базе данных последняя таблица имеет 3 строки, она отображает данные из 3 строк только при условии, что остальные строки остаются пустыми.

Вот коэффициент моего числаOfRowsInSection и cellForRowAtIndexPath

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.

    if(requestType == 2) 
    {       
        if (self.uniqueCityCount > 0) 
        {
            NSString *strCity = [self.arrayCityNames objectAtIndex:section];            //@"EventData" :@"EventCity"
            NSPredicate *predicateSettings =  [NSPredicate predicateWithFormat:@"(EventCity = %@ )",strCity]; 
            if ([self.arrayEventDescription count]>0)
            {
                [self.arrayEventDescription removeAllObjects];
            }
            self.arrayEventDescription = [CoreDataAPIMethods searchObjectsInContext:@"EventData" :predicateSettings :@"EventCity" :YES :self.managedObjectContext];
            return [self.arrayEventDescription count];  
        }
        /*
         if (section == 0)
         {
         NSString *strCity = [self.arrayCityNames objectAtIndex:section];           //@"EventData" :@"EventCity"
         NSPredicate *predicateSettings =  [NSPredicate predicateWithFormat:@"(EventCity = %@ )",strCity]; 
         self.arrayEventDescription = [CoreDataAPIMethods searchObjectsInContext:@"EventData" :predicateSettings :@"EventCity" :YES :self.managedObjectContext];
         return [self.arrayEventDescription count]; 
         }
         else if (section == 1)
         {

         }*/
    }       
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
NSString *CellIdentifier = [@"" stringByAppendingFormat:@"Cell%d",indexPath.row];      
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

cell.backgroundColor = [UIColor clearColor];

if(requestType == 2)
{   
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        //  for (int j = 0 ; j < [self.arrayEventDescription count]; j++)

        //  for(int j=0; j<[tableView numberOfSections]; j++)

        //{

        NSLog(@"at section %d",indexPath.section);
        NSLog(@"at row %d",indexPath.row);
        NSLog(@"array count %d",[self.arrayEventDescription count]);

        if (indexPath.row < [self.arrayEventDescription count]) 
        {


            EventData *data = [self.arrayEventDescription objectAtIndex:indexPath.row];
            //EventData *data = [self.arrayEventDescription objectAtIndex:j];

            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];      


            //  UIView *viewDescription = [[UIView alloc]initWithFrame:CGRectMake(00, 00, 480, 35)];

            //////////////////////    Labels for description of city events from database  ////////////////////////////             

            UILabel *lblEvent = [[UILabel alloc]initWithFrame:CGRectMake(15, 00, 150, 30)];
            lblEvent.font = [UIFont systemFontOfSize:12];
            lblEvent.backgroundColor = [UIColor clearColor];

            UILabel *lblEventAtDate = [[UILabel alloc]initWithFrame:CGRectMake(200, 00, 150, 30)];
            lblEventAtDate.font = [UIFont systemFontOfSize:12];
            lblEventAtDate.backgroundColor = [UIColor clearColor];

            UILabel *lblEventAtSchool = [[UILabel alloc]initWithFrame:CGRectMake(350, 15, 150, 30)];
            lblEventAtSchool.font = [UIFont systemFontOfSize:12];
            lblEventAtSchool.backgroundColor = [UIColor clearColor];

            [cell.contentView addSubview:lblEvent];
            [cell.contentView addSubview:lblEventAtDate];
            [cell.contentView addSubview:lblEventAtSchool];


            lblEvent.text = data.EventName;
            //  lblEventAtDate.text = data.EventDate;
            lblEventAtSchool.text = data.EventPlace;
        }



        //} 
    }
}


// Configure the cell...

return cell;
}

Ответы [ 2 ]

0 голосов
/ 16 августа 2011

Можете ли вы сказать мне, какой тип запроса и когда он будет вызываться (набор возможных значений).

Быстрое решение: сначала вы проверяете условие типа запроса if(requestType == 2) {, а затемзагружают камеру.Этот метод делегата будет вызываться при загрузке таблицы, но тип запроса равен 2. Так что для indexpath.row = 0 & 1 он не зайдет внутрь для загрузки ячейки и загрузится только для requesttype = 2.Так идет загрузка третьего ряда.

0 голосов
/ 16 августа 2011

Во-первых, я переместил все из блока cell == nil, так как повторное использование может не произойти.Посмотрите, решит ли это вашу проблему.

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

{    

NSString *CellIdentifier = [@"" stringByAppendingFormat:@"Cell%d",indexPath.row];      
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];

if(requestType == 2)
{   
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        //  for (int j = 0 ; j < [self.arrayEventDescription count]; j++)

        //  for(int j=0; j<[tableView numberOfSections]; j++)

        //{

        NSLog(@"at section %d",indexPath.section);
        NSLog(@"at row %d",indexPath.row);
        NSLog(@"array count %d",[self.arrayEventDescription count]);





        //} 
    }

    if (indexPath.row < [self.arrayEventDescription count]) 
    {


        EventData *data = [self.arrayEventDescription objectAtIndex:indexPath.row];
        //EventData *data = [self.arrayEventDescription objectAtIndex:j];

        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor clearColor];      


        //  UIView *viewDescription = [[UIView alloc]initWithFrame:CGRectMake(00, 00, 480, 35)];

        //////////////////////    Labels for description of city events from database  ////////////////////////////             

        UILabel *lblEvent = [[UILabel alloc]initWithFrame:CGRectMake(15, 00, 150, 30)];
        lblEvent.font = [UIFont systemFontOfSize:12];
        lblEvent.backgroundColor = [UIColor clearColor];

        UILabel *lblEventAtDate = [[UILabel alloc]initWithFrame:CGRectMake(200, 00, 150, 30)];
        lblEventAtDate.font = [UIFont systemFontOfSize:12];
        lblEventAtDate.backgroundColor = [UIColor clearColor];

        UILabel *lblEventAtSchool = [[UILabel alloc]initWithFrame:CGRectMake(350, 15, 150, 30)];
        lblEventAtSchool.font = [UIFont systemFontOfSize:12];
        lblEventAtSchool.backgroundColor = [UIColor clearColor];

        [cell.contentView addSubview:lblEvent];
        [cell.contentView addSubview:lblEventAtDate];
        [cell.contentView addSubview:lblEventAtSchool];


        lblEvent.text = data.EventName;
        //  lblEventAtDate.text = data.EventDate;
        lblEventAtSchool.text = data.EventPlace;
    }
}


// Configure the cell...

return cell;

}

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