- 是,即使值不会改变新写道:在管理对象上下文仍在发生。因此,
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
谢谢你的努力,但视图控制器不涉及所以这并不能帮助我。除了在每个对象上测试'changedValues'并抛弃非变化之外,是否无法避免通知? –
好吧,'self'可以是NSObject类的任何实例,不一定(甚至通常)是UIViewController。你可以有一个Core Data Helper单例或一个类的简单实例,例如'@interface CoreDataHelper:NSObject' – ystack
我不清楚你的意思。 –