如何保存复选框数据

时间:2015-01-12 13:09:49

标签: ios uitableview checkbox

我创建了UITableView,TableView中的数据从Web服务加载。我在单元格中插入一个复选框。
我想保存已检查单元格的数据。
当我也重新打开应用程序所选复选框保持原样,就像之前一样。

这是我的myTable.m

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath       *)indexPath {
     static NSString *cell1=@"aa";
     CustomCell *cell=[tableView dequeueReusableCellWithIdentifier:cell1];

    if (cell==nil) {

      cell=[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell1];
      NSArray *cellArray=[[NSBundle mainBundle]loadNibNamed:@"CustomCell" owner:nil options:nil];

      for (UIView *view in cellArray) {

         if([view isKindOfClass:[CustomCell class]])
           {
            cell = (CustomCell*)view;             

        }
        }
}

    //cell.textLabel.text=[array objectAtIndex:indexPath.row];
cell.labelcell.text=[array objectAtIndex:indexPath.row];

return cell;

}

CustomCell.h

  #import <UIKit/UIKit.h>

   @interface CustomCell : UITableViewCell{

    BOOL isSelected;
     }


    @property (strong, nonatomic) IBOutlet UILabel *labelcell;

    @property (strong, nonatomic) IBOutlet UIButton *checkButton;

    - (IBAction)checkboxAction:(id)sender;

    @end

CustomCell.m

    - (IBAction)checkboxAction:(id)sender {

       NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];

        if(!isSelected){

          [checkButton setImage:[UIImage imageNamed:@"checked.png"]
                 forState:UIControlStateNormal];

         isSelected = YES;
         [defaults setBool:isSelected forKey:@"boxIsChecked"];

         }
         else if (isSelected){

           [checkButton setImage:[UIImage imageNamed:@"empty-check.png"]
                 forState:UIControlStateNormal];

        isSelected = NO;
        [defaults setBool:isSelected forKey:@"boxIsChecked"];

        }

        [defaults synchronize];
        }
        -(void)checkTheBox{

          if(!isSelected){
            [checkButton setImage:[UIImage imageNamed:@"empty-check.png"]
                 forState:UIControlStateNormal];
          }
           else if (isSelected){

            [checkButton setImage:[UIImage imageNamed:@"checked.png"]
                 forState:UIControlStateNormal];
          }

          }

我尝试使用NSUserDefaults但它正在申请表中的总行数。我想申请个别行,也想保存该行数据。 任何人都可以帮助我。

3 个答案:

答案 0 :(得分:0)

您应该看看如何在设备上保存数据,有两种方法可以做到这一点。

如果您要保存的数据很少,请使用plist(我认为这是您的最佳选择)。

祝你好运。

答案 1 :(得分:0)

如果您想使用用户默认值实现@Chandan,那么

#import "ViewController.h"
#import "CustomTableViewCell.h"

NSString* cellIdentifier = @"CellIdentifier";

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
{

    UITableView *_tableView;
    NSMutableArray *_dataSource;
    NSMutableArray *_checkBoxSelectionArray;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
    [self.view addSubview:_tableView];

    _checkBoxSelectionArray = [[NSMutableArray alloc] init];
    _dataSource = [[NSMutableArray alloc] init];

    for (int i = 0; i < 20; i++) {
        [_dataSource addObject:[NSString stringWithFormat:@"Cell [%d]", i]];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{

    return 1;
}

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

    //user defaults
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray* array = [userDefaults objectForKey:@"checkedStatusArray"];
    if (!array) {
        NSMutableArray* mutArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < _dataSource.count; i++) {
            NSMutableDictionary* checkedDict = [[NSMutableDictionary alloc] init];
            [checkedDict setObject:[NSNumber numberWithBool:NO] forKey:@"checkBoxStatus"];
            [mutArray addObject:checkedDict];
        }

        [userDefaults setObject:mutArray forKey:@"checkedStatusArray"];
    }
    else {
        for (int i = 0; i < _dataSource.count - array.count; i++) {
            NSMutableDictionary* checkedDict = [[NSMutableDictionary alloc] init];
            [checkedDict setObject:[NSNumber numberWithBool:NO] forKey:@"checkBoxStatus"];
            [array addObject:checkedDict];
        }

        [userDefaults setObject:array forKey:@"checkedStatusArray"];
    }

    [userDefaults synchronize];

    return _dataSource.count;
}

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

    CustomTableViewCell* customCell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (customCell == nil) {
        customCell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    customCell.cellLable.text = [_dataSource objectAtIndex:indexPath.row];
    [customCell.cellCheckBox addTarget:self action:@selector(whenCheckBoxTapped:) forControlEvents:UIControlEventTouchUpInside];

    //user defaults
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray* userDefaultsArray = [userDefaults objectForKey:@"checkedStatusArray"];

    NSMutableDictionary* checkedDict = [userDefaultsArray objectAtIndex:indexPath.row];
    if ([[checkedDict objectForKey:@"checkBoxStatus"] boolValue]) {
        [customCell.cellCheckBox setBackgroundImage:[UIImage imageNamed:@"radio_checked"] forState:UIControlStateNormal];
    }
    else {
        [customCell.cellCheckBox setBackgroundImage:[UIImage imageNamed:@"radio_unchecked"] forState:UIControlStateNormal];
    }

    return customCell;
}

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

    [self selectedTableViewCellOrCheckBox:indexPath.row];
}

-(void)whenCheckBoxTapped:(id)sender{

    NSIndexPath *indexPath = [_tableView indexPathForCell:[self returnTableViewCellFromSuperViewHierarchyForView:sender]];
    [self selectedTableViewCellOrCheckBox:indexPath.row];

}

-(UITableViewCell *)returnTableViewCellFromSuperViewHierarchyForView:(UIView *)aView
{

    while (aView.superview != nil) {
        aView = aView.superview;
        if ([aView isKindOfClass:[UITableViewCell class]]) {
            return (UITableViewCell *)aView;
        }
    }

    return nil;
}

-(void)selectedTableViewCellOrCheckBox:(int) index{

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];

    CustomTableViewCell* selectedCell = (CustomTableViewCell*)[_tableView cellForRowAtIndexPath:indexPath];
    [selectedCell.cellCheckBox setBackgroundImage:[UIImage imageNamed:@"radio_checked"] forState:UIControlStateNormal];
    NSLog(@"%d", [selectedCell.cellCheckBox isSelected]);

    //user defaults
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray* userDefaultsArray = [userDefaults objectForKey:@"checkedStatusArray"];

    NSMutableDictionary* checkedDict = [userDefaultsArray objectAtIndex:indexPath.row];

    if ([[checkedDict objectForKey:@"checkBoxStatus"] boolValue]) {

        [checkedDict setObject:[NSNumber numberWithBool:NO] forKey:@"checkBoxStatus"];
        [selectedCell.cellCheckBox setBackgroundImage:[UIImage imageNamed:@"radio_unchecked"] forState:UIControlStateNormal];
    }
    else {
        [checkedDict setObject:[NSNumber numberWithBool:YES] forKey:@"checkBoxStatus"];
        [selectedCell.cellCheckBox setBackgroundImage:[UIImage imageNamed:@"radio_checked"] forState:UIControlStateNormal];
    }

    [userDefaultsArray replaceObjectAtIndex:indexPath.row withObject:checkedDict];
    [userDefaults setObject:userDefaultsArray forKey:@"checkedStatusArray"];
    [userDefaults synchronize];

}

@end

答案 2 :(得分:-1)

@Chandan ..

  

在IOS中有4种方法可以保存数据

 1. SqLite Database
 2. Plist
 3. User Defaults
 4. Core Data

保存在UserDefault中,您可以像这样直接保存数据。 实施例。

//保存Bool值

[Userdefaults setBool:NO forKey:"isUserLogin"];
[Userdefaults synchronize];

//获得Bool值

BOOL islogin=[Userdefaults boolForKey:isUserLogin];

//保存对象

[Userdefaults setObject:[response valueForKey:APPKEY] forKey:APPKEY];
[Userdefaults synchronize];

//获取对象

NSDictionary *postParameter=[NSDictionary dictionaryWithObjectsAndKeys:[Userdefaults objectForKey:"Lat"],@"vLatitude",[Userdefaults objectForKey:"Lon"],@"vLongitude",nil];

&安培;另一种节省数据的最佳方法是使用SqLite数据库...

更多信息点击链接:http://mehul4ever.blogspot.in/2014/12/ios-sqlite-database-insert-update-delete.html

我已解释所有插入,更新和放大从DataBase&amp;删除数据将其显示在表格中或设备中的任何位置。

相关问题