Ashley Rodrigues
Ashley Rodrigues

Reputation: 153

How to save the checkmarks in uitableview and show them when the user comes back again to the view?

I am using the following code for showing the checkmarks in the uitableview

  {
  //  NSArray *tableContents;
    NSMutableArray *selectedMarks; // You need probably to save the selected cells for use in the future.
}
@property (strong, nonatomic) IBOutlet UITableView *languageTableView;
@property (nonatomic, strong) NSArray *tableContents;

@end

@implementation QPLanguageSettingsController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initialisation];
    selectedMarks = [NSMutableArray new];
}
#pragma mark - View Life Cycle

-(void)initialisation
{
    _tableContents = [NSArray arrayWithObjects:@"English",@"Spanish",@"Russian",@"Arabic",@"Portuguese",@"French",@"German",@"German",@"German",@"German",@"German",@"German",@"German",@"German", nil];
}

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

#pragma mark - UITableView delegate & datasources

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 14;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newFriendCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor clearColor];
    [cell setIndentationLevel:3];
    [cell setIndentationWidth:10];
     NSString *text = [_tableContents objectAtIndex:[indexPath row]];
     //cell.isSelected = [selectedMarks containsObject:text] ? YES : NO;
     cell.textLabel.text = text;
     NSDictionary *item = [_tableContents objectAtIndex:indexPath.row];
    if ([selectedMarks containsObject:item])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;

    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //if you want only one cell to be selected use a local NSIndexPath property instead of array. and use the code below
    //self.selectedIndexPath = indexPath;

    //the below code will allow multiple selection
     NSDictionary *item = [_tableContents objectAtIndex:indexPath.row];
    if ([selectedMarks containsObject:item])
    {
        [selectedMarks removeObject:item];
    }
    else
    {
        [selectedMarks addObject:item];
    }
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

But the problem is that when i come again to the view controller all the checkmarks disappears. how to solve it. Remember i am using multiple selection in uitableview.

Upvotes: 1

Views: 236

Answers (4)

KSR
KSR

Reputation: 1709

Use the following code:

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *languagesTableView;

@property (strong, nonatomic) NSArray *languagesArray;

@property (strong, nonatomic) NSMutableArray *checkMarksArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.languagesTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.languagesArray = [NSArray arrayWithObjects:@"English",@"Spanish",@"Russian",@"Arabic",@"Portuguese",@"French",@"German", nil];
    self.checkMarksArray = [[NSMutableArray alloc]init];
    if( [[NSUserDefaults standardUserDefaults]objectForKey:@"selectedRowsArray"])
    {
       self.checkMarksArray = [[[NSUserDefaults standardUserDefaults]objectForKey:@"selectedRowsArray"] mutableCopy];
    }
}


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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.languagesArray.count;

}

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

    UITableViewCell *languagesCell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    languagesCell.textLabel.text = self.languagesArray[indexPath.row];
    if([self.checkMarksArray containsObject:[NSNumber numberWithLong:indexPath.row]])
    {
        languagesCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        languagesCell.accessoryType = UITableViewCellAccessoryNone;
    }

    [[NSUserDefaults standardUserDefaults]setObject:self.checkMarksArray forKey:@"selectedRowsArray"];
    [[NSUserDefaults standardUserDefaults]synchronize];

    return languagesCell;


}

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

    if([self.checkMarksArray containsObject:[NSNumber numberWithLong:indexPath.row]])
    {
        [self.checkMarksArray removeObject:[NSNumber numberWithLong:indexPath.row]];
    }
    else
    {
        [self.checkMarksArray addObject:[NSNumber numberWithLong:indexPath.row]];
    }

    [self.languagesTableView reloadData];
}

@end

Check this GitHub link:

https://github.com/k-sathireddy/TableViewSelectedCheckMarks

Upvotes: 0

poyo fever.
poyo fever.

Reputation: 752

you can create a Singleton and store data on it :

Singleton.h

@interface Singleton : NSObject

@property (nonatomic, strong) NSArray *rowsChecked;

+ (Singleton *)sharedInstance;
+ (NSArray  *)getRowsChecked;
+ (void)setRowsChecked:(NSArray *)rowsChecked;

@end

Singleton.m

    #import "Singleton.h"

@implementation Singleton

        static Singleton *sharedObject;

        + (Singleton *)sharedInstance;
        {
            if (sharedObject == nil) {
                static dispatch_once_t pred;
                dispatch_once(&pred, ^{
                    sharedObject = [[Singleton alloc] init];
                });
            }
            return sharedObject;
        }

        + (NSArray *)getRowsChecked
        {
            Singleton *singleton = [Singleton sharedInstance];
            return singleton.rowsChecked;
        }

        + (void)setRowsChecked:(NSArray *)rowsChecked
        {
            Singleton *singleton = [Singleton sharedInstance];
            singleton.rowsChecked= rowsChecked;
        }

    @end

and to access to your Singleton :

[[Singleton sharedInstance] getRowsChecked]

// or

[[Singleton sharedInstance] setRowsChecked:anArray];

Upvotes: 0

user3182143
user3182143

Reputation: 9589

I tried the to get solution for your question.I got it successfully.It works perfectly.

This is sample one.Try this code.It works fine.

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableViewCheckMarkPreviousSelectionUpdate;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
{
   NSMutableArray *arrProductSelection,*arrProductSelectDeSelectCheckMark;
   NSArray *arrayFetchFromDefaults;
}

@end

@implementation ViewController

@synthesize tableViewCheckMarkPreviousSelectionUpdate;

- (void)viewDidLoad
{
   [super viewDidLoad];
   arrProductSelection = [[NSMutableArray alloc]initWithObjects:@"iPhone",@"iPad",@"iPod",@"iTV",@"iWatch",@"iMac",nil];
}
- (void)didReceiveMemoryWarning
{
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  arrayFetchFromDefaults = [userDefaults objectForKey:@"selectedcheckmark"];
  arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]initWithArray:arrayFetchFromDefaults];
  if(arrProductSelectDeSelectCheckMark.count == 0)
  {
     arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]init];
     for(int j=0;j<[arrProductSelection count];j++)
     {
        [arrProductSelectDeSelectCheckMark addObject:@"deselected"];
     }
   }
   [tableViewCheckMarkPreviousSelectionUpdate reloadData];
}

#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return arrProductSelection.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSString *strCell = @"cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
   if(cell==nil)
   {
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
   }
   if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:@"deselected"])
     cell.accessoryType = UITableViewCellAccessoryNone;
   else
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
   cell.textLabel.text = [arrProductSelection objectAtIndex:indexPath.row];
   return cell;
}

#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    @try
    {
        CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewCheckMarkSelectionUpdate];
        NSIndexPath *indexPath = [tableViewCheckMarkSelectionUpdate indexPathForRowAtPoint:touchPoint];
        NSLog(@"%@",arrProductSelectDeSelectCheckMark);
        if([arrProductSelectDeSelectCheckMark count]==0)
        {
           for(int i=0; i<[arrProductSelection count]; i++)
           {
             [arrProductSelectDeSelectCheckMark addObject:@"deselected"];
           }
        }
        if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:@"deselected"])
        {
           cell.accessoryType = UITableViewCellAccessoryCheckmark;
           [arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:@"selected"];
        }
        else
        {
           cell.accessoryType = UITableViewCellAccessoryNone;
           [arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:@"deselected"];
        }

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:arrProductSelectDeSelectCheckMark forKey:@"selectedcheckmark"];
        [defaults synchronize];
      }
   @catch (NSException *exception) {
    NSLog(@"The exception is-%@",exception);
   }
}
@end

Upvotes: 3

OhadM
OhadM

Reputation: 4803

You have multiple solutions:

  1. Using a rational DB on the device like Core-data or SQLite which actually fits your use case but number 3 is more suitable for your use case.
  2. Using NSUserDefaults:

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default

You can find an example here. But NSUserDefaults is to save settings/config/setup information or perhaps user info and NOT for the use case you need.

  1. Using NSCoder which is in my opinion fits your use case.

Upvotes: 0

Related Questions