Reputation: 2272
My code sets up it's Entity, Context etc and then saves a record, that all works fine. Then I want to save a NEW record but the code overwrites the original record.
How can I write more than one item in the same instance?
AppDelegate *appdelagate = [[UIApplication sharedApplication]delegate];
context = [appdelagate managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"UserData" inManagedObjectContext:context];
NSManagedObject *userData = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[userData setValue:@"Bob" forKey:@"userCD"];
[userData setValue:@"Tall" forKey:@"dataCD"];
// Store in the DB
[context save:&error];
SOME HOW MOVE TO NEXT RECORD
[userData setValue:@"John" forKey:@"userCD"];
[userData setValue:@"Short" forKey:@"dataCD"];
// Store in the DB
[context save:&error];
I am thinking I need to release the userData and declare again... I am also thinking I am missing a great deal and should stop thinking in terms of SQL.
Thanks
Upvotes: 0
Views: 2371
Reputation: 539745
That is because you change the attributes of the first userData
object instead of
creating a new one:
NSManagedObject *userData;
// Create first object:
userData = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[userData setValue:@"Bob" forKey:@"userCD"];
[userData setValue:@"Tall" forKey:@"dataCD"];
[context save:&error];
// [userData release]; only if you don't compile with ARC
// Create second object:
userData = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[userData setValue:@"John" forKey:@"userCD"];
[userData setValue:@"Short" forKey:@"dataCD"];
[context save:&error];
// [userData release]; only if you don't compile with ARC
Upvotes: 2