2010-05-28 122 views
1

我正在使用謂詞在覈心數據中查找對象。我可以成功找到我想要的對象,但我還需要獲取該對象的indexPath,以便可以爲該對象推送一個詳細信息視圖。目前,我有一個讓我的對象下面的代碼:iPhone:獲取Predicate對象的indexPath

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Ride" inManagedObjectContext:self.managedObjectContext]]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@ AND addressFull = %@", view.annotation.title, view.annotation.subtitle]; 
    [fetchRequest setPredicate:predicate]; 
    NSMutableArray *sortDescriptors = [NSMutableArray array]; 
    [sortDescriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]]; 
    [sortDescriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"addressFull" ascending:YES] autorelease]]; 
    [fetchRequest setSortDescriptors:sortDescriptors]; 
    [fetchRequest setReturnsObjectsAsFaults:NO]; 
    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"title", @"addressFull", nil]]; 
    NSError *error = nil; 
    NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
    // Sohow what record we returned 
    NSLog(@"%@",[fetchedItems objectAtIndex:0]); 

所以,我可以正確得到我的對象到一個數組。 但是,如何將該對象轉換爲indexPath?

回答

2

索引路徑只是一組索引,例如, {0, 2}可能代表一個索引路徑,指向表視圖的第一部分和第三行 - 假設您的數組數據的表視圖表示是您的最終目標。

該索引路徑可能指向數組中的任何特定對象,具體取決於將路徑轉換爲數組索引的方式。

如果你想任意索引路徑,這是很容易:

NSUInteger myFirstIndex = 0; 
NSUInteger mySecondIndex = 2; 
NSUInteger myIndices[] = {myFirstIndex, mySecondIndex}; 
NSIndexPath *myIndexPath = [[NSIndexPath alloc] initWithIndexes:myIndices length:2]; 
// ...do someting with myIndexPath... 
[myIndexPath release]; 

所以,你需要做的是找出你的陣列結構如何轉化爲章節和行(再次什麼,假設你想製作表格視圖表示)。

另一種選擇是使用NSFetchedResultsController來爲您處理表視圖更新 - 它將爲您處理索引路徑,具體取決於您如何對部分進行分區。

+0

是的,你是對的,我想在UITableView中展示它。只需要在細節視圖中滑動單擊的地圖註記。 – 2010-05-28 01:45:09

+0

我建議你把你的數據提取到一個'NSFetchedResultsController'中,讓它執行表視圖更新。它消除了將核心數據獲取結果連接到表視圖的大約99%的工作。 – 2010-05-28 01:48:21

+0

我得到它的工作,只需要用我的根控制器初始化。 – 2010-05-28 02:14:45