2014-02-16 39 views
0

我想遍歷sortDescriptors NSArray並刪除不符合特定條件的對象。請問有人能告訴我如何正確地做到這一點。如何從NSFetchRequest sortDescriptors中刪除對象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   
     } 
} 
+1

陣列'request.sortDescriptors'doesn't握住你獲取的數據,但只有你添加到它的排序描述符。您需要首先將數據提取到新數組中並遍歷該數組。如果你想刪除對象,你將需要一個'NSMutableArray。但是您必須從商店中刪除它們,而不是從提取數組中刪除它們! – Volker

+0

Volker:謝謝,我不想從商店中刪除它們,只想刪除一些不符合request.sortDescriptors標準的對象,然後使用initWithFetchRequest:request將其加載到NSFetchedResultsController中。刪除對象後,我可以將NSMutableArray分配回request.sortDescriptors嗎? – newdev1

+1

你不能用'NSFetchedResultsController'來做到這一點,因爲這個謂詞不能被轉換成'SQL'語句 –

回答

0

我相信你這裏有兩個問題:

  • NSArray是不可變的,因此你不能從中刪除項目。您應該將其轉換爲NSMutableArray
  • 在枚舉過程中,您不應該從數組中刪除項目。但是,您可以使用for(int i=0;i<[yourArray count];i++)遍歷數組。
0

試試這個代碼

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 
+1

在使用NSFastEnumeration進行迭代時,您不應該修改陣列 - 這幾乎肯定會崩潰或導致尷尬的錯誤 –

+0

沒錯,我已經根據該代碼更改了代碼。 – Pawan

+0

這是如何被接受的答案?它甚至沒有任何意義 - request.sortDescriptors返回的是一個'NSSortDescriptor'對象而不是'CarsInventory'對象的數組,因此''NSSortDescriptor'不會響應'isCarWithin5FileRadius':' –