HardikDabhi
HardikDabhi

Reputation: 2952

How can I remove data from the array when uncheck the cell in UITableview?

I have made one sample demo. Like selected cell print after "Done"button clicked. It is working fine.

Code is

@synthesize arrayContainer,filteredRecipes,myTableView,filtered,selectedRaw;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.arrayContainer = [[NSMutableArray alloc]initWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine", nil];
    self.selectedRaw = [[NSMutableArray alloc]init];

}

-(IBAction)printSelectedItem:(id)sender
{
    NSLog(@"The Selected Items are %@",self.selectedRaw);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(filtered == YES)
    {
        return self.filteredRecipes.count;

    }
    else
    {
        return self.arrayContainer.count;

    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];

    if(filtered == YES)
    {
        cell.textLabel.text = [self.filteredRecipes objectAtIndex:indexPath.row];

    }
    else
    {
        cell.textLabel.text = [self.arrayContainer objectAtIndex:indexPath.row];

    }


    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];


    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

        cell.accessoryType = UITableViewCellAccessoryNone;
        // NSString *string = [self.selectedRaw objectAtIndex:indexPath.row];

        [self.selectedRaw removeObjectAtIndex:indexPath.row];

    } else {

        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        NSString *temp = [self.arrayContainer objectAtIndex:indexPath.row];
        [self.selectedRaw addObject:temp];
    }

}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{

    [searchBar setShowsCancelButton:YES animated:YES];
}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

    if([searchText length] == 0)
    {
        self.filtered   = NO;
    }
    else
    {
        self.filtered = YES;

        self.filteredRecipes = [[NSArray alloc]init];

        NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",searchText];

        filteredRecipes = [self.arrayContainer filteredArrayUsingPredicate:resultPredicate];
    }

    [self.myTableView reloadData];
}

Question is

-> When I print selected row of table view ,Displayed in log perfectly.

-> But when I deselected those selected item it gives me n error.

Please give me solution.

My another question is when I have searched particular item (selected) it gives me selected item perfectly,then i deselect item after I have canceled searching then it gives me again selected item which I did deselect earlier.

Output image

enter image description here

selected Raw

enter image description here

Unchecked second raw

enter image description here

enter image description here

enter image description here

Upvotes: 0

Views: 545

Answers (3)

CodeChanger
CodeChanger

Reputation: 8351

You have to remove data based on Object not based on Index so here you can go with below code:

1st you have to check filter condition in your didselect method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];


    if(filtered == YES)
      {
          if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

             cell.accessoryType = UITableViewCellAccessoryNone;
            [self.selectedRaw removeObject:[self.filteredRecipes objectAtIndex:indexPath.row]];

          } else {

             cell.accessoryType = UITableViewCellAccessoryCheckmark;
             [self.selectedRaw addObject:[self.filteredRecipes objectAtIndex:indexPath.row]]
          }


    }
    else
    {
       if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

          cell.accessoryType = UITableViewCellAccessoryNone;

          [self.selectedRaw removeObject:[self.arrayContainer objectAtIndex:indexPath.row]];

       } else {

          cell.accessoryType = UITableViewCellAccessoryCheckmark;
          [self.selectedRaw addObject:[self.arrayContainer objectAtIndex:indexPath.row]]
       }

    }
}

2nd Problem solution:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];

    if(filtered == YES)
    {
        cell.textLabel.text = [self.filteredRecipes objectAtIndex:indexPath.row];
        if([selectedRaw containsObject:self.filteredRecipes[indexPath.row]] ){
          cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
          cell.accessoryType = UITableViewCellAccessoryNone;
        }

    }
    else
    {
        cell.textLabel.text = [self.arrayContainer objectAtIndex:indexPath.row];
        if([selectedRaw containsObject:self.arrayContainer[indexPath.row]] ){
          cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
          cell.accessoryType = UITableViewCellAccessoryNone;
        }

    }


    return cell;
}

Hope This will helps you.

Upvotes: 1

Gulliva
Gulliva

Reputation: 488

So please try this.

#import "SecondViewController.h"

@interface SecondViewController ()
@property(nonatomic,strong)NSArray *arrayContainer;
@property(nonatomic,strong)NSArray *filteredRecipes;
@property(nonatomic,strong)NSMutableArray *selectedRaw;
@property(nonatomic,assign)BOOL filtered;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _arrayContainer = @[@"One",@"Two",@"Three",@"Four"];
//      _arrayContainer = [[NSMutableArray alloc]initWithArray:];
    _selectedRaw = [[NSMutableArray alloc]init];
    [self.tableView reloadData];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_filtered)
        return _filteredRecipes.count;
    else
        return _arrayContainer.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    if(_filtered){
        NSString *tmp = [_filteredRecipes objectAtIndex:indexPath.row];
        cell.textLabel.text = tmp;
        if([_selectedRaw containsObject:tmp])
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        else
            cell.accessoryType = UITableViewCellAccessoryNone;
    }else{
        NSString *tmp = [_arrayContainer objectAtIndex:indexPath.row];
        cell.textLabel.text = tmp;
        if([_selectedRaw containsObject:tmp])
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        else
            cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{

    if(self.filtered){
        if([self.selectedRaw containsObject:[self.filteredRecipes objectAtIndex:indexPath.row]]){
             [self.selectedRaw removeObjectAtIndex:[self.selectedRaw indexOfObject:[self.filteredRecipes objectAtIndex:indexPath.row]]];
        }else{
            NSString *temp = [self.filteredRecipes objectAtIndex:indexPath.row];
            [self.selectedRaw addObject:temp];
        }
    }else{
        if([self.selectedRaw containsObject:[self.arrayContainer objectAtIndex:indexPath.row]]){
           [self.selectedRaw removeObjectAtIndex:[self.selectedRaw indexOfObject:[self.arrayContainer objectAtIndex:indexPath.row]]];
        }else{
            NSString *temp = [self.arrayContainer objectAtIndex:indexPath.row];
            [self.selectedRaw addObject:temp];
        }
    }
    [self.tableView reloadData];

}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if([searchText length] == 0)
    {
        self.filtered   = NO;
    }
    else
    {
        self.filtered = YES;


        NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",searchText];

        _filteredRecipes = [self.arrayContainer filteredArrayUsingPredicate:resultPredicate];
    }

    [self.tableView reloadData];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    _filtered = !_filtered;
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    _filtered = !_filtered;
}

@end

Upvotes: 2

Amit Verma
Amit Verma

Reputation: 1413

1: You have to take array with dictionary with parameter like

 [{
  value : “One”,
  state : “Check”
  },
  {
  value : “Two”,
  state : “UnCheck”
  }
  ]

then on cellForRowAtindexParth

 if (self.selectedRaw[indexPath.row] as !     NSDictionary).value(forKey:”state”) as! String == “Check”{
  //change to check mark
   }
  else{
  //change to UnCheck mark
  }

At DidSelectRowAtIndexPath

 if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

 if (arr[indexPath.row] as ! NSDictionary).value(forKey:”state”) as!          String == “Check”{
   //change state value to UnCheck
 }else{
    //change state value to Check
     }

     }

2:On second point you need to do same work

Upvotes: 0

Related Questions