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

标签 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

最佳答案

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

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

关于ios - 当用户从 uitableview 到 nsuserdefaults 选择时如何保存多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459063/

相关文章:

带有不完整 TLS 握手的 iOS ECONNRESET - 生成 errSSLClosedNoNotify

objective-c - 将时间转换为 float

ios - 采访 Que Tableview reuseIdentifier 内部工作

iphone - UITableView - 延迟加载联系人图像

ios - UISearchBar 上方的 UITableView 部分

ios - ionic 1 ios 发布构建失败 Visual studio 2015

ios - Swift 委托(delegate)和协议(protocol)不起作用

ios - 为 UITableViewCell 绘制虚线边框底部

ios - 在实时 iphone 摄像头中使用 OpenCV 检测物体的存在

ios - NSURLSessionDataTask dataTaskWithURL 完成处理程序未被调用