每次与服务器同步时,都会刷新CoreData对象的所有字段。
即使没有任何变化,我仍然会在代码中的其他地方收到NSManagedObjectContextObjectsDidChangeNotification
。
当我在刷新对象后添加下面的代码时,事情就像我想要的那样。但是为什么CoreData不能对此进行排序呢?
if (object.changedValues.count == 0)
{
[object.managedObjectContext refreshObject:object mergeChanges:NO];
}
答案 0 :(得分:-2)
NSManagedObjectContextObjectsDidChangeNotification
被解雇。考虑使用NSFetchedResultsController作为:
@interface CoreDataHelper : NSObject < NSFetchedResultsControllerDelegate >
@property (nonatomic, readonly) NSManagedObjectContext *context;
+ (instancetype)sharedInstance;
@end
@implementation
@synthesize context = _context;
+ (instancetype)sharedInstance{
static dispatch_once_t once;
static CoreDataHelper *sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [self new];
});
return sharedInstance;
}
- (NSManagedObjectContext *)context{
if (_context != nil) {
return _context;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; // you know what goes in PSC here, right?
if (!coordinator) {
NSLOG(@"Argh! coordinator == nil");
return nil;
}
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_context setPersistentStoreCoordinator:coordinator];
return _context;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
/*
This function will be invoked by the OS whenever a Managed Object changes.
Keep in mind that this will be invoked on the Managed Object Context Queue.
This is the place where your logic to be performed whenever a object changes needs to be.
*/
}
@end
//现在在您的档案中
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[CoreDataHelper sharedInstance].context sectionNameKeyPath:nil cacheName:nil];
fetchedResultsController.delegate = [CoreDataHelper sharedInstance];
NSError *error;
if (![fetchedResultsController performFetch:&error]){
NSLOG(@"fetch error %@", error);
}
现在,由于我们已将self
作为fetchedResultsController
的代理联系起来,self
需要符合NSFetchedResultsControllerDelegate
协议。
您选择覆盖任何可选方法,最直接的是:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller