0

Я реализую в своем PFQueryTableViewController (Use Parse.com) работы Swipe to Delete. Когда я иду, чтобы выполнить действие отмены ячейки, эта ошибка возникает, и приложение падает.Проведите, чтобы удалить строку, не занятую

Unigo 10/08/2013 15: 40: 50,683 [29142: A0B] Пользователь онлайн: между Unigo 10/08/2013 15: 40: 54.495 [29142: A0B] * отказ Assertion в - [UITableView _endCellAnimationsWithContext:],/SourceCache/UIKit_Sim/UIKit-2903.2/UITableView.m 1330 Unigo 10/08/2013 15: 40: 54.499 [29142: a0b] * Завершение приложения два для неотображаемого исключение «NSInternalInconsistencyException», причина : 'Неверно обновление: недопустимое количество строк в разделе 0. Количество строк , содержащихся в существующем разделе после обновления (5), должно быть равно количеству строк, содержащихся в этом разделе перед обновлением (5 ), плюс или минус количество строк, вставленных или удаленных из этого (0 вставлено, 1 удалено) и плюс или минус количество строк перемещено в или из раздела «Той» (0 перемещено, 0 выведено). '

Помогите мне выяснить, где я ошибаюсь?

@implementation FFEsami 
@synthesize FFNewLabelEsameInAttesa,FFViewEsameInAttesaAvviso,clock,ShowPanel,ArrayMutable; 

-(id)initWithCoder:(NSCoder *)FFaDecoder { 
    self = [super initWithCoder:FFaDecoder]; 
    if (self) { 
     self.parseClassName = FF_ESAMI_CLASS; 
     self.pullToRefreshEnabled = YES; 

    } 
    return self; 
} 


#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self SetGraphSectionView]; 
    [self queryForTable]; 
    self.tableView.allowsSelectionDuringEditing = YES; 
    self.tableView.allowsMultipleSelectionDuringEditing = YES; 

    // Uncomment the following line to preserve selection between presentations. 
    // self.clearsSelectionOnViewWillAppear = NO; 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    self.navigationItem.leftBarButtonItem = self.editButtonItem; 
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]]; 
} 


- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 








- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; 

    [self loadObjects]; 

} 



#pragma mark - Parse 

- (void)objectsDidLoad:(NSError *)error { 
    [super objectsDidLoad:error]; 

    // This method is called every time objects are loaded from Parse via the PFQuery 
} 

- (void)objectsWillLoad { 
    [super objectsWillLoad]; 

    // This method is called before a PFQuery is fired to get more objects 
} 

- (PFQuery *)queryForTable { 
    PFQuery *FFQueryPerTableView = [PFQuery queryWithClassName:FF_ESAMI_CLASS ]; 
    [FFQueryPerTableView whereKey: FF_ESAMI_USER equalTo: [PFUser currentUser]]; 
    [FFQueryPerTableView orderByDescending:FF_ESAMI_DATA_STRING]; 

    if ([self.objects count] == 0) { 
    } 
    return FFQueryPerTableView; 
} 

-(void)SetGraphSectionView { 
    FFViewEsameInAttesaAvviso =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)] ; 
    FFNewLabelEsameInAttesa = [[UILabel alloc]initWithFrame:CGRectMake(60, -1, 200, 50)]; 
    FFNewLabelEsameInAttesa.numberOfLines = 2; 
    FFNewLabelEsameInAttesa.textAlignment = NSTextAlignmentLeft; 
    FFNewLabelEsameInAttesa.textAlignment = NSTextAlignmentLeft; 
    FFNewLabelEsameInAttesa.lineBreakMode = NSLineBreakByTruncatingTail; 
    clock = [[UIImageView alloc] initWithFrame:CGRectMake(17, 11, 25, 25)]; 
    // ShowPanel = [[UIImageView alloc] initWithFrame:CGRectMake(280, 27, 20, 20)]; 

} 
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
     return 50.0; 
} 
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 


if(section==0){ 

PFQuery *query = [PFQuery queryWithClassName:FF_ESAMI_CLASS]; 
[query whereKey:FF_ESAMI_USER equalTo:[PFUser currentUser]]; 
[query whereKey:FF_ESAMI_STATUS equalTo:[NSNumber numberWithBool:YES]]; 
[query orderByAscending:FF_ESAMI_DATA_STRING]; 
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) { 

    if (!object) { 
     NSString *titolo = [NSString stringWithFormat:@"Nessun esame imminente"]; 
     FFNewLabelEsameInAttesa.text = titolo; 
     FFNewLabelEsameInAttesa.font = [UIFont fontWithName:@"HelveticaNeue" size:13]; 
     FFNewLabelEsameInAttesa.textColor = [UIColor grayColor]; 
     FFNewLabelEsameInAttesa.numberOfLines = 2; 

     FFViewEsameInAttesaAvviso.backgroundColor = [UIColor clearColor]; 
     clock.image= [UIImage imageNamed:@"FFIMG_InAttesa"]; 

    } else { 
     NSString *titolo = [NSString stringWithFormat:@"%@", [object objectForKey:FF_ESAMI_TITOLO]]; 
     FFNewLabelEsameInAttesa.text = titolo; 
     FFNewLabelEsameInAttesa.font = [UIFont fontWithName:@"HelveticaNeue" size:13]; 
     FFNewLabelEsameInAttesa.textColor = [UIColor whiteColor]; 


     FFViewEsameInAttesaAvviso.backgroundColor = [UIColor colorWithRed:(203/255.0) green:(162/255.0) blue:(86/255.0) alpha:(0.90)]; 
     clock.image= [UIImage imageNamed:@"FFIMG_InAttesaBianco"]; } 
}]; 
ShowPanel.image= [UIImage imageNamed:@"FFDownView"]; 
[FFViewEsameInAttesaAvviso addSubview:FFNewLabelEsameInAttesa]; 
[FFViewEsameInAttesaAvviso addSubview:clock]; 
    [FFViewEsameInAttesaAvviso addSubview:ShowPanel]; 
} 

return FFViewEsameInAttesaAvviso; 

} 

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    return 0; 
} 

- (FFCustomListaEsamiCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object { 

    FFCustomListaEsamiCell *cell = (FFCustomListaEsamiCell *)[self.tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    if (!cell) { 
     cell = [[FFCustomListaEsamiCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]; 
    } 

    NSString *text = [object objectForKey:FF_ESAMI_TITOLO]; 
    cell.FFTitoloEsameLabel.numberOfLines = 2; 
    cell.FFTitoloEsameLabel.text = text; 


    NSDateFormatter *FFDataFormattata = [[NSDateFormatter alloc] init]; 
    [FFDataFormattata setDateFormat:FF_DATE_FORMATTER]; 
    cell.FFDataEsameLabel.text = [NSString stringWithFormat: @"%@",[FFDataFormattata stringFromDate:[object objectForKey:FF_ESAMI_DATA_STRING]]]; 


    PFObject *rowObject = [self.objects objectAtIndex:indexPath.row]; 

    if([[rowObject objectForKey:FF_ESAMI_STATUS] boolValue]) 
    { 
     //DATO CONVALIDATO 
     cell.last.image = [UIImage imageNamed:@"FFIMG_InAttesa"]; 


     /*UIImage *btn = [UIImage imageNamed:@"FF_ChechOk"]; 
     [cell.FFInserisciConvalida setImage:btn forState:UIControlStateNormal]; 
     [cell.FFInserisciConvalida addTarget:self 
             action:@selector(FFConvalidaDato) 
          forControlEvents:UIControlEventTouchUpInside]; 
     [cell.FFAltreAzioni addTarget:self 
           action:@selector(ActionSheetForStateInAttesa) 
        forControlEvents:UIControlEventTouchUpInside];*/ 





    } else { 

     //DATO NON CONVALIDATO 
     //UIImage *btn = [UIImage imageNamed:@"FFIMG_ClockTAG"]; 
     /* [cell.FFInserisciConvalida setImage:btn forState:UIControlStateNormal]; 
     [cell.FFInserisciConvalida addTarget:self 
             action:@selector(FFMettiInAttesa) 
          forControlEvents:UIControlEventTouchUpInside]; 
     [cell.FFAltreAzioni addTarget:self 
           action:@selector(ActionSheetForStateConvalidato) 
        forControlEvents:UIControlEventTouchUpInside];*/ 


    } 


    return cell; 
} 



/* 
// Override if you need to change the ordering of objects in the table. 
- (PFObject *)objectAtIndex:(NSIndexPath *)indexPath { 
return [objects objectAtIndex:indexPath.row]; 
} 
*/ 

/* 
// Override to customize the look of the cell that allows the user to load the next page of objects. 
// The default implementation is a UITableViewCellStyleDefault cell with simple labels. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForNextPageAtIndexPath:(NSIndexPath *)indexPath { 
static NSString *CellIdentifier = @"NextPage"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

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

cell.selectionStyle = UITableViewCellSelectionStyleNone; 
cell.textLabel.text = @"Load more..."; 

return cell; 
} 
*/ 

#pragma mark - Table view data source 


// Override to support conditional editing of the table view. 
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
// Return NO if you do not want the specified item to be editable. 
return YES; 
} 




// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
if (editingStyle == UITableViewCellEditingStyleDelete) { 


    PFObject *object = [self.objects objectAtIndex:indexPath.row]; 
    [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { 

     [self loadObjects]; 
    }];[tableView reloadRowsAtIndexPaths:[tableView indexPathsForVisibleRows] withRowAnimation:UITableViewRowAnimationFade]; 
    // [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 





} 
else if (editingStyle == UITableViewCellEditingStyleInsert) { 
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

} 
} 



// Override to support rearranging the table view. 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{ 
} 



// Override to support conditional rearranging of the table view. 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
// Return NO if you do not want the item to be re-orderable. 
return YES; 
} 



#pragma mark - Table view delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [super tableView:tableView didSelectRowAtIndexPath:indexPath]; 
} 


@end 

ответ

1

У вас есть этот код:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    return 0; 
} 

который говорит таблицу, чтобы иметь 0 клеток в нем после обновления, когда таблица ожидает 4. Если вы используете статические клетки в раскадровке затем вам не следует выполнять функцию numberOfRowsInSection.

Если вы удалите этот код, то проблем не возникнет.

EDIT: Или, если вам нужна функция numberOfRowsInSection, вам необходимо подключить источник данных к представлению таблицы. Это позволит вам вернуть счет источника данных. Затем, когда вы удаляете строку, вы удаляете соответствующий объект в своем источнике данных, чтобы счетчик был на 1 меньше, чем был ранее.

+0

Здравствуйте и спасибо за ответ ... Потом я пытался изменить с self.objects.count объектов NSArray находится в PfqueryTableViewController , но продолжает crasharee не понимаю, почему ... P.S. ячейки динамичны, как я могу это сделать? – kAiN

+0

Вы пытались запустить его с удаленным кодом? Причина, по которой он выходит из строя, состоит в том, что ваш UITableView ожидает, что в этом разделе будет 4 строки после удаления 1. Код в моем ответе указывает, что ваша таблица должна иметь 0 строк в секции после удаления 1. Таким образом, исключение возникает, потому что 0! = 4. Или результат 'self.objects.count' не равен 4. Попробуйте удалить функцию numberOfRowsInSection. –

+1

Прошу прощения, если вы не понимаете, но у меня мало опыта, но я изучаю: D В любом случае я решил, и я все еще работаю с анимацией. Я полностью удалил и модифицировал numberOfRowInSection UITableViewCellEditingStyleDelete следующим образом: [tableView reloadRowsAtIndexPaths: [tableView indexPathsForVisibleRows] withRowAnimation: UITableViewRowAnimationFade]; [tableView endUpdates]; PFObject * object = [self.objects objectAtIndex: indexPath.row]; [объект deleteInBackgroundWithBlock:^(BOOL преуспел, ошибка NSError *) {[self loadObjects];}]; Большое спасибо Майку +1 за вас – kAiN

Смежные вопросы