I am trying to add objects to a persistent store in Core Data.
When the user taps the save button I initialize a new object which is a subclass of the NSManagedObject class and in the data model.Profile *newProfile = [[Profile alloc] initWithEntity:[NSEntityDescription entityForName:@"Profile" inManagedObjectContext:MOC] insertIntoManagedObjectContext:MOC];
[newProfile setValue:userName.text forKey:@"userName"];
[newProfile setValue:txtInstitution.text forKey:@"institution"];
I can verify in the console that the values for userName and txtInstitution are correct and what expected, and also that the object has the proper attributes. However, it seems to save the object with the same values as whatever the first object saved was. Only one profile is created at a time, and the MOC is saved after each profile is added in this way.
Also, when a table tries to populate 开发者_如何学JAVAwith data from the persistent store it will create rows as though are as many objects in the store as I have created at that time, but they will all have the same values.
Are you sure you are retrieving the objects from the store correctly? This sounds like it might be an issue with the fetch request you use to get the data out of the store and/or an issue with the way you display the data.
Is there any particular reason you're not using the designated initialiser for NSManagedObjects?
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context
So you should use:
Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:self.MOC];
Also make sure you are accessing your MOC via its property (self.MOC, not the ivar directly) as if you are using the templates provided by Apple you will notice the MOC is lazily loaded via its getter method.
精彩评论