1

我有一個情況,我有一個ObjectA的列表。 ObjectAObjectB有多對多的關係。我需要遍歷ObjectA的列表並存儲ObjectB引用的所有名稱。通過CoreData ManagedObject的關係循環

我目前做這點實際的for循環的方式爲使用執行時間儀器的89.5%:

for (ObjectA *a in listA) { 
     [names removeAllObjects]; 
     for (ObjectB *b in a.objectBs) { //This is 89.5% of the execution time 
      [names addObject:b.name]; 
     } 
} 

有什麼辦法來處理這更好的?

回答

0

這不是你要求的答案,但也許它解決了你的問題。你爲什麼需要這些名字?

難道你不能使用謂詞循環通過嵌套列表嗎?我不知道性能是否更好,但是因爲您使用的是CoreData,我會嘗試。

我使用了一個謂詞循環遍歷像這樣的嵌套列表。我用Xcode3的謂詞編輯器做了它。但Xcode4也有一位編輯。

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"ANY keywords.word contains[cd] %@", self.searchBar.text]; 

    [fetchedResultsControllerSearch.fetchRequest setPredicate:predicate]; 



NSError *error = nil; 
if (![[self fetchedResultsControllerSearch] performFetch:&error]) { 
    // Handle error 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    exit(-1); // Fail 
}  
0

我對你的循環有點困惑。結果在names的唯一結果將是最後a.objectBslistA中的b.name

如何嘗試喜歡的東西:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"objectB"]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.objectAs contains %@", listA); 
fetchRequest.predicate = predicate; 

// execute 

這將返回所有在他們objectA關係的objectAobjectBs的。您可以在需要該名稱的位置致電objectB.name

PS你的例子的命名使得這5000萬次更難以遵循。