Below is my code snippet:
NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Login" inManagedObjectContext:self.managedObjectContext];
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"userid==%@ AND password==%@",useridentered, passwordentered];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *anyError=Nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:request error:&anyError];
Login *login = [fetchedObjects objectAtIndex:0];
Information *information = [NSEntityDescription insertNewObjectForEntityForName:@"Information" inManagedObjectContext:self.managedObjectContext];
login.information = information;
login.information.title = informationTitleTextView.text;
login.information.info_1 = information1textview.text;
login.information.info_2 = information2textview.text;
[self.managedObjectContext save:nil]; // write to database
NSLog(@"login.information %@",login.information.title);
NSLog(@"login.title %@", login.userid);
[self.delegate savebuttontapped:self];
The problem is, it works fine for the first time. But when i again add information for the same user it overwrites the existing one. How to make sure that it gets written to next line?
You are creating a new managed object for the information (new DB row):
And then you assign it to the user.
This does not remove the old information from the DB, but the user loses relationship with it.
I suppose that what you want is having more than one
Informationinstances connected to oneLogininstance.That means you have to open your Managed Object Model and change the one-to-one relationship into one-to-many relationship.
Then your code will be:
or