如何从 NSFetchRequest sortDescriptors NSArray 中删除对象



我想遍历排序描述符NSArray并删除不符合特定条件的对象。这里有人可以告诉我如何正确做到这一点。

NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@“CarsInventory”];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@“model” ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
for (CarsInventory* carInfo in request.sortDescriptors)
{
        if (![self isCarWithin5FileRadius:carInfo.location])
        {
            [request.sortDescriptors delete: bookInfo]; // CRASH         
        }
}

我相信你这里有两个问题:

  • NSArray是不可变的,因此您无法从中删除项目。您应该将其转换为 NSMutableArray .
  • 不应在枚举期间从数组中删除项。但是,您可以使用 for(int i=0;i<[yourArray count];i++) 循环访问数组。

试试这段代码

NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@“CarsInventory”];
NSArray *sortedArray = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@“model” ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
NSMutableArray *mutArray=[NSMutableArray arrayWithCapacity:[sortedArray count]];
for (CarsInventory* carInfo in sortedArray)
{
    if ([self isCarWithin5FileRadius:carInfo.location])
    {
        [mutArray addObject:carInfo];// add it to mutable array
    }
}
NSLog(@"New Mut Array--%@",mutArray); //log the final list

最新更新