2013-04-24 37 views
1

我有一個正在與核心數據的用戶o增加自己的細胞一個UITableView ...但我希望他們能夠重新排序TableViewCells他們想要的方式...我使用現在的代碼,但每當重排出來,說我去添加其他細胞,它會返回下面,如果你失去了常規狀態...圖片...與核心數據的TableView重新排序UITableViewCells

下面是代碼:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.row == 0) // Don't move the first row 
     return NO; 

    return YES; 
} 

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ 

id ob = [_devices objectAtIndex:destinationIndexPath.row]; 

     [_devices replaceObjectAtIndex:destinationIndexPath.row withObject:[_devices objectAtIndex:sourceIndexPath.row]]; 
     [_devices replaceObjectAtIndex:sourceIndexPath.row withObject:ob]; 
} 

Before reorder

During reorder

Adding new cell

After adding the new cell (back to date ordering)

回答

2

你應該在你的實體,以便您的排序順序是持續增加的訂單屬性。

則需要通過命令鍵進行排序的表格視圖數據源。

很可能你的_devices陣列得到重新初始化與核心數據獲取請求的結果,並因此完成修改的次序會丟失。

更新了評論

假設你有一個名爲Device的實體是一個子類的NSManagedObject使用指定屬性order你可以做到以下幾點。當你執行

NSSortDescriptor *orderSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]; 
[devicesFetchRequest setSortDescriptors:@[orderSortDescriptor]]; 

那麼你的讀取請求,並捕捉你的_devices陣列的結果,他們將被順序屬性進行排序。

然後在- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath你將需要對受影響的實體更新的順序屬性。

如果從位置5移動設備位置2,那麼你需要通過+1更新2-4位置的實體和移動實體2,這有可能會效率低下大數據快速但對於小數據集它應該表現良好。

+0

那麼這怎麼做呢? PS,這是在該.m文件 – 2013-04-24 22:19:19

+0

@property(強)的NSMutableArray *的設備的頂部; – 2013-04-24 22:19:59

+0

已更新的答案,希望對您有所幫助。 – 2013-04-24 22:30:31