- 是,即使值不會改變新寫道:在管理對象上下文仍在發生。因此,
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
我不清楚你的意思。 –