如何在目标c中未选择表格视图单元格时删除数组值?

时间:2017-03-29 11:23:27

标签: objective-c

这是我的代码

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}

当选择表格单元格值时,所选值存储在valueselectedcell数组中,它正常工作。现在,当我取消选择行时,如何删除数组中的值。

2 个答案:

答案 0 :(得分:2)

我没有足够的声誉来发表评论,因此我将其作为答案发布。来自@Dipankar Das的回答是完全正确的,我只想回答OP的评论中提出的问题。

如果未选中的单元格值与单元格的选定值相同,则表示它将在数组中删除所选值,如何验证它。

更新didSelectRowAtIndexPath&amp;这样的didDeselectRowAtIndexPath方法 -

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *indexofselectedcell = [[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    [indexofselectedcell addObject:indexPath];

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}


-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([indexofselectedcell containsObject: indexPath]) {
        NSInteger anIndex=[indexofselectedcell indexOfObject:indexPath];
        [indexofselectedcell removeObjectAtIndex:anIndex];
        [valueofselectedcell removeObjectAtIndex:anIndex];
    }
}

答案 1 :(得分:1)

使用Tableview's didDeselectRowAtIndexPath委托方法:

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    if ([valueofselectedcell containsObject: test])
    {
        [valueofselectedcell removeObject:test];
    }
}