0

我正在使用 Storybord,我得到了一个带有复选框按钮的表格视图。

我正在使用 NSUserDefaults 来保存我的复选框按钮的状态,我尝试使用 Core Data 保存它,但我不知道如何使用简单的方法 NSUserDefaults 更好。

并且复选框按钮工作得很好,但问题是它没有保存复选框按钮的状态!

当我关闭应用程序并再次打开它时,它没有保存。

任何人都可以在这里帮助我我尽我所能来解决这个问题但没有运气

这是我的代码

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

@property (nonatomic,assign) BOOL checked;


  @synthesize myButton,checked;


 - (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
checked = [defaults boolForKey:@"boxIsChecked"];
[defaults synchronize];
[self checkTheBox];

}

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

// Configure the cell...
NSManagedObject *device = [self.Work objectAtIndex:indexPath.row];

[cell.textLabel setText= [Work valueForKey:@"name"]



myButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[myButton setFrame:CGRectMake(260,2,40,40)];
myButton.tag = indexPath.row;
[myButton setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(ButtonCheckMark:) 
forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:myButton];
cell.selectionStyle = UITableViewCellSelectionStyleNone;


return cell;
}


- (IBAction)ButtonCheckMark:(id)sender {

myButton = (UIButton *)sender;
NSLog(@"playButton %li" , (long)myButton.tag);

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if (!checked) {
    [myButton setImage:
    [UIImage imageNamed:@"checkBoxMarked.png"]  forState:UIControlStateNormal];
    checked = YES;
    [defaults setBool:checked forKey:@"boxIsChecked"];
}

else if (checked) {
    [myButton setImage:
   [UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
    checked = NO;
    [defaults setBool:checked forKey:@"boxIsChecked"];
  }

[defaults synchronize];

   }
 - (void) checkTheBox {
if (!checked) {
    [myButton setImage:
  [UIImage imageNamed:@"checkBox.png"]   forState:UIControlStateNormal];
   }

else if (checked) {

    [myButton setImage:
  [UIImage imageNamed:@"checkBoxMarked.png"]   forState:UIControlStateNormal];
   }
   }
4

0 回答 0