iOS从数组中删除对象

时间:2013-12-05 14:02:55

标签: ios objective-c arrays

我正在从plist加载一系列项目。用户可以选择任何项目并将其添加到屏幕上显示的新项目数组中。

我这样做但是用户也可以从任何行删除播放器。我的问题是当用户删除它对列表进行洗牌的对象时。我想把那一行留空的地方。

我的删除代码:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *user_id = [prefs objectForKey:@"user_id"];
    NSString *fixture_id = [prefs objectForKey:@"fixture_id"];

    // Get path to documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);


    [self.usersSelectionArray removeObjectAtIndex:indexPath.row];

    if (self.usersSelectionArray == nil) {

        // disable swipe to delete?
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if ([paths count] > 0)
    {
        // Path to save array data
        NSString  *arrayPath = [[paths objectAtIndex:0]
                                stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@",user_id, fixture_id]];

        // Write array
        [self.usersSelectionArray writeToFile:arrayPath atomically:YES];
    }

    // If blank array delete the file as not required
    if (self.usersSelectionArray.count == 0) {

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@", user_id, fixture_id]];

        NSError *error;
        if(![[NSFileManager defaultManager] removeItemAtPath:path error:&error])
        {
            //TODO: Handle/Log error
        }
    }

    [self.tableView reloadData];
}

它还检查计数是否为0并删除plist,如果需要,在加载时重新创建。

2 个答案:

答案 0 :(得分:0)

而不是[self.usersSelectionArray removeObjectAtIndex:indexPath.row];,请尝试[self.usersSelectionArray replaceObjectAtIndex:indexPath.row withObject:[NSNull null]];。这将保留行,但几乎不包含任何内容

答案 1 :(得分:0)

所以你想要从数据数组中删除一个对象,但在表中为它保留一个空单元格?

在这种情况下,我建议用NSNull实例替换已删除的对象。

[myMutableArray replaceObjectAtIndex:index withObject:[NSNull null]];

然后,您可以检查单元格的对象是否为NSNull,并在cellForRowAtIndexPath:数据源方法中返回一个空单元格。

id object = // get the correct object from your data array, depending on the index
BOOL isEmpty = [object isKindOfClass:[NSNull class]];
if (isEmpty) {
    // return empty table cell
else {
    // return a normal cell
}