尝试重新排序NSMutableArray时的运行时异常

时间:2013-11-04 17:39:11

标签: ios objective-c core-data nsmutablearray

我有一个UITableViewController,它显示存储在Core Data中的用户定义的收藏夹列表。加载表视图时,托管对象将放置在可变数组中。要构造可变数组,我使用以下静态方法(在一个单独的类中):

+(NSMutableArray*)getAllFavorites{
    NSManagedObjectContext *context = [[FavesDataModel sharedDataModel] mainContext];
    NSFetchRequest *fetchReq = [[NSFetchRequest alloc] init];

    NSSortDescriptor *sortByIndex = [[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES];
    [fetchReq setSortDescriptors:[NSArray arrayWithObject:sortByIndex]];

    NSEntityDescription *entity = [NSEntityDescription entityForName:[Favorite entityName] inManagedObjectContext:context];
    [fetchReq setEntity:entity];

    NSError *err = nil;
    return (NSMutableArray*)[context executeFetchRequest:fetchReq error:&err];
}

在我的表视图中,我需要允许用户重新排序行。我已经验证了我的可变托管对象的可变数组是完整的,但是,当我尝试删除给定索引处的对象时,在运行时抛出异常( - [_ PFArray removeObjectAtIndex:]:发送到实例的无法识别的选择器) 。以下是导致异常的代码:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    [self setEditing:YES animated:YES];        
    NSInteger rowIndex = fromIndexPath.row;
    Favorite *fave = [allFavoriteObjects objectAtIndex:rowIndex];

    [allFavoriteObjects removeObjectAtIndex:rowIndex]; // exception thrown here
    [allFavoriteObjects insertObject:fave atIndex:toIndexPath.row];
}

有什么建议吗? THX!

3 个答案:

答案 0 :(得分:2)

NSManagedObjectContext的executeFetchRequest可能正在返回不可变数组。试试这个。

return [[context executeFetchRequest:fetchReq error:&err] mutableCopy];

答案 1 :(得分:2)

而不是

return (NSMutableArray*)[context executeFetchRequest:fetchReq error:&err];

尝试使用

return [[context executeFetchRequest:fetchReq error:&err] mutableCopy];

答案 2 :(得分:0)

执行此操作时使用辅助NSMutableArray,因为您的类中使用了allFavoriteObjects,并且tableview中的各种方法都可以访问它们。