hanumanDev
hanumanDev

Reputation: 6614

How to keep the checkmark in a UITableView after the view disappears

I have a uitableview that's displaying multiple selections with a custom checkmark. When selected the rows value is save using NSUserDefaults. The problem is that despite the values being saved the checkmarks disappear from the table cell rows. I can't figure out why.

thanks for any help, I'm really stuck on this.

Here's the .h code:

    @interface CategoriesViewController : UITableViewController {

    NSString *selectedCategoryTableString;

    NSString *jsonStringCategory;

    int prev;

}

// arForTable array will hold the JSON results from the api

@property (nonatomic, retain) NSArray *arForTable;
@property (nonatomic, retain) NSMutableArray *arForIPs;

@property (nonatomic, retain) NSMutableArray *categorySelected;

@property (nonatomic, retain) NSString *jsonStringCategory;
@property(nonatomic, retain) UIView *accessoryView;

@end

and the .m code:

@implementation CategoriesViewController
@synthesize jsonStringCategory;
@synthesize arForTable = _arForTable;
@synthesize arForIPs = _arForIPs;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.arForIPs=[NSMutableArray array];

    self.categorySelected = [[NSMutableArray alloc] init];

    [self reloadMain];

    self.tableView.allowsMultipleSelection = YES;
}

-(void) reloadMain {

    jsonString = @"http:///******";

    // Download the JSON
    NSString *jsonString = [NSString
                            stringWithContentsOfURL:[NSURL URLWithString:jsonString]
                            encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
                            error:nil];

    NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];

    // Create parser
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *results = [parser objectWithString:jsonString error:nil];

    itemsTMP = [results objectForKey:@"results"];

    self.arForTable = [itemsTMP copy];

    [self.tableView reloadData];

}

#pragma mark - Table view data source

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

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arForTable count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        [cell.textLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
        [cell.detailTextLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
        cell.accessoryView.hidden = NO;

    }

    UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-tick.png"]] ;
    UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]] ;

    if([self.arForIPs containsObject:indexPath]){
        cell.accessoryView = cellAccessoryImageView;
    } else {
        cell.accessoryView = cellAccessoryNoneImageView;
    }

    // Get item from tableData
    NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];

    // encoding fix
    NSString *utf8StringTitle = [item objectForKey:@"name"];

    NSString *correctStringTitle = [NSString stringWithCString:[utf8StringTitle cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];

    cell.textLabel.text = [correctStringTitle capitalizedString];

    NSNumber *num = [item objectForKey:@"id"];

    cell.detailTextLabel.text = [num stringValue];

    cell.detailTextLabel.hidden = YES;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if([self.arForIPs containsObject:indexPath]){
        [self.arForIPs removeObject:indexPath];

        [self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:@"id"]];

    } else {
        [self.arForIPs addObject:indexPath];

        [self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:@"id"]];

        NSLog(@"%@ categorySelected",self.categorySelected);

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

        NSLog(@"%@ defaults categorySelected",[defaults arrayForKey:@"selectedCategoryTableString"]);

        NSString *string = [self.categorySelected componentsJoinedByString:@","];

        [defaults setObject:string forKey:@"selectedCategoryTableString"];

        NSLog(@"%@ STRING",string);

    }

    [tableView reloadData];
}



-(void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:NO];

    [self.navigationController setNavigationBarHidden:YES animated:NO];

    self.navigationController.toolbarHidden = YES;

}

Upvotes: 1

Views: 1877

Answers (2)

aks.knit1108
aks.knit1108

Reputation: 1305

Since in your table there is only one section. Try this approach and this will help you certainly.

In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath write following code;

    if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
        cell.accessoryView = cellAccessoryImageView;
    } else {
        cell.accessoryView = cellAccessoryNoneImageView;
    }

And in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath write code as below,

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

Upvotes: 1

SAPLogix
SAPLogix

Reputation: 1744

First of all your code has lots of memory leaks, please do use the static analyzer and/or instruments to fix them, few for them are pretty obvious like you initialized the SBJSON parser and did not release it, itemsTMP is another.

I have rewritten your code to be much more efficient and memory friendly:

@interface CategoriesViewController : UITableViewController
{
    NSArray *_items;
    NSMutableArray *_selectedItems;

    UIImageView *cellAccessoryImageView;
}

@end



@implementation CategoriesViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _selectedItems = [NSMutableArray new];

    cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-tick.png"]] ;

    [self reloadMain];

    self.tableView.allowsMultipleSelection = YES;
}

- (void)reloadMain
{    
    NSString *jsonString = @"http:///******";

    // Download the JSON
    jsonString = [NSString
                        stringWithContentsOfURL:[NSURL URLWithString:jsonString]
                        encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
                        error:nil];

    // Create parser
    SBJSON *parser = [SBJSON new];
    NSDictionary *results = [parser objectWithString:jsonString error:nil];

    if (_items) [_items release];
    _items = [[results objectForKey:@"results"] copy];

    [parser release];

    [self.tableView reloadData];
}

#pragma mark - Table view data source

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

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_items count];
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

        [cell.textLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
        [cell.detailTextLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
        cell.accessoryView.hidden = NO;

    }

    NSDictionary *item = [_items objectAtIndex:indexPath.row];

    if ([_selectedItems containsObject:item])
    {
        // preloaded image will help you have smoother scrolling 
        cell.accessoryView = cellAccessoryImageView;
    }
    else
    {
        cell.accessoryView = nil;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    // Get item from tableData
    cell.textLabel.text = [[NSString stringWithCString:[[item objectForKey:@"name"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] capitalizedString];
    cell.detailTextLabel.text = [[item objectForKey:@"id"] stringValue];
    cell.detailTextLabel.hidden = YES;

    item = nil;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSDictionary *item = [_items objectAtIndex:indexPath.row];
    if ([_selectedItems containsObject:item])
    {
        [_selectedItems removeObject:item];
    }
    else
    {
        [_selectedItems addObject:item];
    }
    item = nil;

    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)dealloc
{
    [_selectedItems release];
    [cellAccessoryImageView release];

    [super dealloc];
}

@end

Upvotes: 1

Related Questions