当用户从uitableview选择nsuserdefaults时,如何保存多个项目?

时间:2013-01-22 12:55:09

标签: ios objective-c uitableview nsuserdefaults

我正在尝试保存用户从uitableview到nsuserdefaults选择的任何项目。此时只保存最新的选择。我希望用户能够选择他们想要的任何行,然后保存到nsuserdefaults,然后在应用程序的任何位置使用该信息。

感谢您的帮助

这是我的代码:

   - (void)viewDidLoad
{
    [super viewDidLoad];


    // categories array
    listOfCategories = [[NSMutableArray alloc] init];

    [listOfCategories addObject:@"Food & Drinks"];
    [listOfCategories addObject:@"Beauty & Wellness"];
    [listOfCategories addObject:@"Sports & Fun Activities"];
    [listOfCategories addObject:@"Labor & Services"];
    [listOfCategories addObject:@"Clothes & Accessories"];
    [listOfCategories addObject:@"Education & Training"];
    [listOfCategories addObject:@"Products"];

    // add label
    UIView *viewForHeader = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
    UILabel *categoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0,80,30)];
    categoryLabel.text = @"Select all:";

    [categoryLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
    categoryLabel.textColor = [UIColor lightGrayColor];

    // add switch
    onoff = [[UISwitch alloc] initWithFrame: CGRectMake(100.0f, 0.0f, 100.0f, 0.0f)];
    [onoff addTarget: self action: @selector(flipSwitch:) forControlEvents:UIControlEventValueChanged];

    [viewForHeader addSubview:onoff];

    [viewForHeader addSubview:categoryLabel];
    self.tableView.tableHeaderView = viewForHeader;

}

// uiswitch button
- (IBAction) flipSwitch: (id) sender {
    onoff = (UISwitch *) sender;
    NSLog(@"%@", onoff.on ? @"On" : @"Off");

    if (onoff.on) {
        for (NSInteger s = 0; s < self.tableView.numberOfSections; s++) {
            for (NSInteger r = 0; r < [self.tableView numberOfRowsInSection:s]; r++) {
                [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:r inSection:s]
                                            animated:NO
                                      scrollPosition:UITableViewScrollPositionNone];
            }
        }
    }
}

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

#pragma mark - Table view data source

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

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

    // Return the number of rows in the section.
    return [listOfCategories count];
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }        // Configure the cell...

    NSString *cellValue = [listOfCategories objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;

    [cell.textLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];

    return cell;
}

#pragma mark - Table view delegate

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

    int index = indexPath.row; id obj = [listOfCategories objectAtIndex:index];


    //This toggles the checkmark
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];


    if (cell.accessoryType == UITableViewCellAccessoryNone)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        UIImage *image = [UIImage imageNamed:@"icon-tick.png"];

        UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];

        [downloadButton setImage:image forState:UIControlStateNormal];
        [downloadButton setFrame:CGRectMake(0, 0, 19, 19)];
        [downloadButton setBackgroundColor:[UIColor clearColor]];
        [tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        //This sets the array

    } else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;

        UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [downloadButton setTitle:@"" forState:UIControlStateNormal];
        [downloadButton setFrame:CGRectMake(0, 0, 0, 0)];
        [tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;


    }

    // Save text of the selected cell:
    UITableViewCell *cellSelected = [tableView cellForRowAtIndexPath:indexPath];

    if ([cellSelected.textLabel.text isEqualToString:@"Food & Drinks"]) {
        NSString *valueToSave = cellSelected.textLabel.text;
        [[NSUserDefaults standardUserDefaults]
         setObject:valueToSave forKey:@"preferenceName"];

    }

    NSString *valueToSave = cellSelected.textLabel.text;
    [[NSUserDefaults standardUserDefaults]
     setObject:valueToSave forKey:@"preferenceName"];


    NSString *savedValue = [[NSUserDefaults standardUserDefaults]
                            stringForKey:@"preferenceName"];

    NSLog(@"savedValue %@", savedValue);

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // Customize archiver here
    [archiver encodeObject:obj forKey:@"keyForYourArrayOfNSIndexPathObjects"];
    [archiver finishEncoding];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"keyForYourArrayOfNSIndexPathObjects"];


    NSKeyedUnarchiver *unarchiver;
    unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:
                  [[NSUserDefaults standardUserDefaults] objectForKey:@"keyForYourArrayOfNSIndexPathObjects"]];
    // Customize unarchiver here
    categoryItemSelected = [unarchiver decodeObjectForKey:@"keyForYourArrayOfNSIndexPathObjects"];
    [unarchiver finishDecoding];

    NSLog(@"list of categories selected %@", categoryItemSelected);


}

@end

1 个答案:

答案 0 :(得分:1)

问题是因为您覆盖了以前保存的数据。 首先,您需要加载已保存的数据:

NSKeyedUnarchiver *unarchiver;
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:
              [[NSUserDefaults standardUserDefaults] objectForKey:@"keyForYourArrayOfNSIndexPathObjects"]];
// Customize unarchiver here
categoryItemSelected = [unarchiver decodeObjectForKey:@"keyForYourArrayOfNSIndexPathObjects"];
[unarchiver finishDecoding];
if (categoryItemSelected == nil) {
    //If it isn't been created - then create new array
}

然后添加新对象:

[categoryItemSelected addObject: obj];

然后将其保存回UserDefautls