Reputation: 2526
In Core Data, is there some trick to saving changes to managed objects' attributes when the changes were made with setPrimitiveValue versus the object's regular accessor methods?
I've switched to using setPrimitiveValue and setPrimitiveAttributeName in a few scenarios in order to avoid triggering my FRC's notification methods (controllerWillChangeContent, controllerDidChangeObject, etc.). In both cases, after making changes to the core data objects and saving the managed object context, the changes look like they were made (i.e I can see the changes with NSLog) but they are actually lost (i.e. if I exit the application in the simulator and rerun it, the FRC reloads, and the attributes I thought I changed are gone).
The save code is copied from Apple examples, and the managed object classes for my Core Data entities are as-generated by Xcode. Everything I've read from Apple and on this site suggests this is a valid use of the setPrimitive methods, though I admit I must be lacking a some understanding of how these setPrimitive functions really work...
Code:
// header file for Managed Object sub class generated by xcode from my core data entity:
#import <CoreData/CoreData.h>
@interface PlannedItem : NSManagedObject
{
}
@property (nonatomic, retain) NSNumber * ptType;
@property (nonatomic, retain) NSNumber * whenOrder;
@end
// .m file for Managed Object subclass
#import "PlannedItem.h"
@implementation PlannedItem
@dynamic ptType;
@dynamic whenOrder;
@end
// trying to use setPrimitiveValue or even setPrimitiveWhenOrder to modify
// this is in my view controller
// p is a pointer to PlannedItem
int oldOrder = [p.whenOrder intValue];
[p setPrimitiveValue:[NSNumber numberWithInt:(oldOrder +1)] forKey:@"whenOrder"];
// later on in same method, save is executed.
if (![[self managedObjectContext] save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
NSLog(@"Saved");
Thanks for any tips
Upvotes: 0
Views: 1810
Reputation: 6545
If you don't want the code in the notification handlers to execute (BTW, why would you want that?), it might be easier to disable that, instead of completely avoiding the notifications. Also, remember that Core Data uses those notifications to update your relationships and maintain coherence in your model when you make changes.
In your view controller, setup a boolean and set it according to your need to execute the notification handler code or not. Then, in your handlers check that flag, e.g.:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
if (notificationIgnored) {
return;
}
// rest of the code...
}
Upvotes: 2