2013-03-26 82 views
1

我知道這個問題之前已經問過,但是,我仍然困惑如何實現與核心數據項目中的UITableView單元重新排序。下面提到的代碼我用我的項目重新安排了TableView單元格。重新排列後的單元在覈心數據中不受影響。我怎樣才能更新重新排列tableview單元格後的coredata記錄

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath 
     toIndexPath:(NSIndexPath *)toIndexPath 
{ 
NSInteger sourceRow = fromIndexPath.row; 
     NSInteger destRow = toIndexPath.row; 
     Question *cat1=[questionsArray objectAtIndex:sourceRow]; 
     [questionsArray removeObjectAtIndex:sourceRow]; 
     [questionsArray insertObject:cat1 atIndex:destRow]; 
     [self.cardsTable setEditing:NO animated: YES]; 
     [cardsTable reloadData]; 
} 

回答

0

首先,您必須將索引保存到您的NSManagedObject中。

當你插入一個新的對象請務必設置索引是lastIndex的+ 1

你取的排序索引對象之後。

當您重新排序單元格時,還必須將索引設置爲對象。請注意,因爲您可能必須將索引更改爲所有對象。

示例:您將第一個單元格移動到最後位置。在這種情況下,所有索引都會更改。 FirstCell取最後一個索引,其他所有索引取oldIndex-1。

我完成編輯迭代到您的數據源數組,然後將對象索引設置爲迭代索引後,

+0

謝謝@Alex Terente – VasuIppili 2013-03-26 07:37:27

2

如果您可以定位iOS 5.0或更高版本,那麼您可以使用NSOrderedSet來維護對象的順序。請記住,使用此方法的效率遠低於我在下面建議的其他方法(按照Apple的文檔)。欲瞭解更多信息,請查詢Core Data Release Notes for iOS 5

如果您需要在5.0之前支持iOS版本,或者想要使用更高效的方法,那麼您應該在實體中創建一個額外的整數屬性,並手動維護其中的實體對象的索引添加或重新排列。當顯示對象的時候,你應該根據這個新屬性對它們進行排序,然後你就全部設置好了。例如,這是你的moveRowAtIndexPath方法應該怎麼那麼像:

- (void)moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath sortProperty:(NSString*)sortProperty 
{ 
    NSMutableArray *allFRCObjects = [[self.fetchedResultsController fetchedObjects] mutableCopy]; 

    NSManagedObject *sourceObject = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath]; 

    // Remove the object we're moving from the array. 
    [allFRCObjects removeObject:sourceObject]; 
    // Now re-insert it at the destination. 
    [allFRCObjects insertObject:sourceObject atIndex:[destinationIndexPath row]]; 

    // Now update all the orderAttribute values for all objects 
    // (this could be much more optimized, but I left it like this for simplicity) 
    int i = 0; 
    for (NSManagedObject *mo in allFRCObjects) 
    { 
     // orderAttribute is the integer attribute where you store the order 
     [mo setValue:[NSNumber numberWithInt:i++] forKey:@"orderAttribute"]; 
    } 
} 

最後,如果你發現這個太多的體力勞動,那麼我真的建議使用免費的Sensible TableView框架。該框架不僅會自動爲您維護訂單,還會根據您實體的屬性及其與其他實體的關係生成所有表視圖單元格。在我看來,絕對是一個很棒的節省時間。我也知道另一個庫叫UIOrderedTableView,但我從來沒有使用過,所以我不能推薦它(前一個框架也更受歡迎)。

相關問題