[英]How do I change NSFetchResultController array that holds my objects to different indexes for my objects?
我有一種方法可以用來將表格視圖中的單元格保存並移動到其他索引,如下所示:
- (void)moveTableView:(FMMoveTableView *)tableView moveRowFromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSArray *allObjects = [self.fetchedResultController fetchedObjects];
//array to hold the new order
NSMutableArray * arrayCorectOrder = [NSMutableArray new];
//the target object that is in the index we are moving from
Target *target = [self.fetchedResultController objectAtIndexPath:fromIndexPath];
}
我有一個coreDataStack類,該類負責處理所有核心數據(創建singelton),如下所示:
#import "CoreDataStack.h"
@implementation CoreDataStack
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
+ (instancetype)defaultStack {
static CoreDataStack *defaultStack;
static dispatch_once_t onceTocken;
dispatch_once (&onceTocken, ^{
defaultStack = [[self alloc] init];
});
return defaultStack;
}
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "digitalCrown.Lister" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Lister" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Lister.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
@end
每當我將新對象添加到核心數據時,我都會這樣做:
- (void)insertTeget {
CoreDataStack *stack = [CoreDataStack defaultStack];
Target *target = [NSEntityDescription insertNewObjectForEntityForName:@"Target" inManagedObjectContext:stack.managedObjectContext];
if (self.myTextView.text != nil) {
target.body = self.myTextView.text;
target.time = [NSDate date];
}
[stack saveContext];
}
在表視圖中,當我獲取數據時,我這樣做:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"StackTableViewCell";
Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];
StackTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"StackTableViewCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
cell.cellLabel.text = target.body;
cell.cellLabel.font = [UIFont fontWithName:@"Candara-Bold" size:20];
cell.showsReorderControl = YES;
// Configure the cell...
return cell;
}
這是我在表視圖控制器類中的fetchresultconroller / fetch請求配置:
- (NSFetchRequest *)targetsFetchRequest {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Target"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
return fetchRequest;
}
- (NSFetchedResultsController *)fetchedResultController {
if (_fetchedResultController != nil) {
return _fetchedResultController;
}
CoreDataStack *stack = [CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [self targetsFetchRequest];
_fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:stack.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultController.delegate = self;
return _fetchedResultController;
}
現在我要檢查訂單是否已更改,因此我需要在數據庫中更改訂單...
我該怎么做呢?
謝謝!
我建議您考慮向實體Target
添加另一個屬性,也許將其稱為“ sortOrder
”?
當您獲取結果時,請考慮按sortOrder
排序。
為了使這項工作有效,您將需要在創建每個實體時設置sortOrder
值。 這應該相對簡單...在創建實體之前完成對fetchedResults
的計數,假設您的下一個sortOrder
值等於計數值加1。
在indexPath.row
移動行時,可以使用代碼將受影響的單元格的sortOrder
值重新分配為等於indexPath.row
屬性。
保存后,您的新排序順序應保持不變。
根據我的評論,提取的結果控制器將每個對象的indexPath基於基礎提取的排序順序-在您的情況下為time
。 如果您希望用戶能夠覆蓋它,並對行進行重新排序,則將FRC更改為使用其他排序順序。 (日期型)的新屬性添加到您的實體,名為sortTime
,並修改targetsFetchRequest
方法使用sortTime
作為排序鍵。
每當您添加新的Target
, sortTime
同時設置sortTime
。 在對行進行重新排序時,請設置sortTime
的值,以確保FRC將目標放置在新的indexPath上。 像這樣:
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
Target *targetToMove = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath];
if (destinationIndexPath.row == 0) {
// to move to row 0, the new sortTime can be any value
// that is less than the sortTime of the Target currently at
// row 0
Target *targetAtRow0 = [self.fetchedResultsController objectAtIndexPath:destinationIndexPath];
targetToMove.sortTime = [targetAtRow0.sortTime dateByAddingTimeInterval:-1];
} else {
// for any other row, set the sortTime to be half way
// between the sortTime for the row before the new position
// and the sortTime for the row at the new position
Target *targetBefore = [self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:(destinationIndexPath.row-1) inSection:destinationIndexPath.section]];
Target *targetAfter = [self.fetchedResultsController objectAtIndexPath:destinationIndexPath];
double lowerTimeInterval = [targetBefore.sortTime timeIntervalSinceReferenceDate];
double upperTimeInterval = [targetAfter.sortTime timeIntervalSinceReferenceDate];
double newInterval = (lowerTimeInterval + upperTimeInterval)/2;
NSDate *newSortTime = [NSDate dateWithTimeIntervalSinceReferenceDate:newInterval];
targetToMove.sortTime = newSortTime;
}
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"SaveContext: error %@, %@", error, [error userInfo]);
abort();
}
}
這應該觸發您的FRC委托方法來執行必要的表視圖更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.