0
請仔細閱讀代碼並告訴我我在這裏做錯了什麼。如何在重新排序TableView時更改CoreData的索引?
TableViewController.m
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:context];
NSFetchRequest *fetchrequest = [[NSFetchRequest alloc]initWithEntityName:entity];
_devices = [[context executeFetchRequest:fetchrequest error:nil]mutableCopy];
[self.tableView reloadData]; // When TableView is reloading the data in tableview updating according to the data stored via CoreData.
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
if (fromIndexPath != toIndexPath) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *device = [self.devices objectAtIndex:fromIndexPath.row];
NSString *str1 = [device valueForKey:@"text1"];
NSLog(@"%@",str1);
[self.devices removeObject:device];
[self.devices insertObject:device atIndex:[toIndexPath row]];
// int i = 0;
// for (NSManagedObject *mo in self.devices)
// {
// NSManagedObject *new = [self.devices objectAtIndex:i];
// NSString *check = [new valueForKey:@"text1"];
// NSLog(@"%@",check);
// NSString *check1 = [new valueForKey:@"text2"];
// NSLog(@"%@",check1);
// NSString *check2 = [new valueForKey:@"text3"];
// NSLog(@"%@",check2);
// [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text1"]] forKey:@"text1"];
// [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text2"]] forKey:@"text2"];
// [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text3"]] forKey:@"text3"];
// i++;
// }
NSError *error;
if(![context save:&error]){
NSLog(@"%@ %@",error, [error localizedDescription]);
}
}
}
我有實體名稱:設備和列名:文本1,文本2,文字3
我不想在覈心數據的數據進行排序,其實我想移動TableView中的行,我想更新保存在列text1,text2,text3中的數據的索引。總的來說,tableview中有5行,我只是想更新相對於更新的tableview索引值的索引。
我已經嘗試過該鏈接的對象。當從數據庫獲取值時,它將按照升序或降序對記錄進行重新排序。 –
如果您將displayOrder屬性添加到實體,並在將數據顯示到表視圖之前對displayOrder進行排序,那麼這不會爲您的問題服務 –
確切地說,現在我已經獲得了教程。我現在就試試這個。謝謝... –