Добавление NSUserDefaults в контрольный список iPhone

Я чертовски новичок в разработке для iPhone и пытаюсь составить контрольный список с постоянными данными. Я использую таблицу с контрольным списком, используя [код из этого урока]. 1

Я пытался самостоятельно в течение недели или двух пытаться заставить это работать с NSUserDefaults, но, как я уже сказал, я довольно новичок, и хотя я предпочитаю выяснять это с помощью Google, я либо не Я не знаю, как искать то, что я хочу, или я еще недостаточно умен, чтобы понять это из того, что я нашел. Как правило, часть контрольного списка работает, все ячейки получают соответствующий аксессуар, когда отмечены и не отмечены, но я хочу, чтобы они оставались постоянными до конца.

Я знаю, что это довольно интересный вопрос, поэтому очень ОЧЕНЬ помогло бы, если бы кто-то мог опубликовать код для того, что мне нужно, но любая помощь, которую я могу получить, была бы очень признательна.

Изменить: добавлен код

- (void)tableView:(UITableView *)tableView  didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self tableView: self.tableView  accessoryButtonTappedForRowWithIndexPath: indexPath];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCustomCellID = @"MyCellID";
    UITableViewCell *cell = [tableView    dequeueReusableCellWithIdentifier:kCustomCellID];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }

    NSMutableDictionary *item = [dataArray bjectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"text"];

    [item setObject:cell forKey:@"cell"];

    BOOL checked = [[item objectForKey:@"checked"] boolValue];
    UIImage *image = (checked) ? [UIImage   imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    button.frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal];

    [button addTarget:self action:@selector(checkButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;

    return cell;
}

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil)
    {
        [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];

    BOOL checked = [[item objectForKey:@"checked"] boolValue];

    [item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"];

    UITableViewCell *cell = [item objectForKey:@"cell"];
    UIButton *button = (UIButton *)cell.accessoryView;

    UIImage *newImage = (checked) ? [UIImage imageNamed:@"unchecked.png"] : [UIImage imageNamed:@"checked.png"];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];
}

1 ответ

Вот пример использования NSUserDefaults

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Set a value
[defaults setBool:YES forKey:@"check1"];
//Save immediately
[defaults synchronize];

//Retrieve the value for check1
BOOL retrieved = [defaults boolForKey:@"check1"];

Обновить

Если ваш dataArray содержит только словари с bools и строками, вы можете сохранить весь dataArray в NSUserDefaults, Следующий код не протестирован, но должен быть близок к тому, что вам нужно для сохранения ваших значений.

-(id)yourInitMethod
{
    dataArray = [(NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:@"dataArrayKey"] mutableCopy];
    //Replace dictionaries with a mutable copy
    for(int i = 0; i < [dataArray count]; i++)
    {
        //Your dictionary that you want to be mutable
        NSMutableDictionary *aCopy = [(NSDictionary*)[dataArray objectAtIndex:i] mutableCopy];
        [dataArray replaceObjectAtIndex:i withObject:aCopy];
        [aCopy release];
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];

    BOOL checked = [[item objectForKey:@"checked"] boolValue];

    [item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //Save the updated data array
    [defaults setObject:dataArray forKey:@"dataArrayKey"];
    [defaults synchronize];
}
Другие вопросы по тегам