Core data with to-many relationship - iphone

Hello I am saving number of lyrics paragraph for song Entity. now I want to update that lyrics
I used below code to update value. but it is creating new record.. and also tell to delete
- (void)editLyrics {
[editBarbutton setTitle:#"Save"];
lyrics = [NSEntityDescription insertNewObjectForEntityForName:#"Lyrics" inManagedObjectContext:managedObjectContext];
lyrics.songLyrics = lyricsTextview.text;
lyrics.startTime = startTimeText.text;
lyrics.endTime = endTimeText.text;
lyrics.lyricsSong = song;
NSError *error;
// here's where the actual save happens, and if it doesn't we print something out to the onsole
if (![managedObjectContext save:&error])
{
NSLog(#"Problem saving: %#", [error localizedDescription]);
}
}

You have to get present object before:
NSError *error = nil;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Lyrics"
inManagedObjectContext:self.moc]];
[request setPredicate:[NSPredicate predicateWithFormat:#"something what u like to filter"]];
NSArray *lyrics = [self.moc executeFetchRequest:request error:&error];
if (error) NSLog(#"Failed to executeFetchRequest to data store: %# in function:%#", [error localizedDescription],NSStringFromSelector(_cmd));
lyrics = [lyrics lastObject]

Related

NSSet takes just the last value from my for set

i try to fetch the members from the entity "Teilnehmer" and then i want to save it to another entity "Buchungsteilnehmer" with a relationship to "buchung".
the problem is, that the nsset function saves just the last name and put it to a relationship with my entity "buchung". but i want to store all the members within the for statement into a relationship with "buchung".
Can you help me please
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Teilnehmer" inManagedObjectContext:context];
[request setEntity:entity];
NSArray *events = [context executeFetchRequest:request error:nil];
for (Teilnehmer *teil in events) {
teilnehmer = [NSEntityDescription insertNewObjectForEntityForName:#"Buchungsteilnehmer" inManagedObjectContext:context];
teilnehmer.name=teil.name;
NSLog(#"Name der Teilnehmer lautet: %#",teil.name);
NSError *error;
if (![context save:&error])
{
NSLog(#"Fehler beim hinzufügen : %#", [error localizedDescription]);
}
}
NSSet *set = [NSSet setWithObject:teilnehmer];
NSLog(#"SET: %#",set);
buchung.buchungsteilnehmer=set;
NSError *error;
if (![context save:&error])
{
NSLog(#"Fehler beim hinzufügen : %#", [error localizedDescription]);
}
You create your set with only one object so how do you expect it to have more than one object ?
Change your code as follows :
NSMutableSet *set = [[NSMutableSet alloc] init];
for (Teilnehmer *teil in events) {
teilnehmer = [NSEntityDescription insertNewObjectForEntityForName:#"Buchungsteilnehmer" inManagedObjectContext:context];
teilnehmer.name=teil.name;
NSLog(#"Name der Teilnehmer lautet: %#",teil.name);
NSError *error;
if (![context save:&error])
{
NSLog(#"Fehler beim hinzufügen : %#", [error localizedDescription]);
} else {
[set addObject:teilnehmer];
}
}
buchung.buchungsteilnehmer=set; // I assume you synthesized this member so it retains set
[set release];
Create a NSMutableSet before your for loop starts. Call addObject on the set each time you insert a new entity.

Trouble saving Core Data objects via iOS

I was saving core data objects successfully until now. In this code, I'm searching for some objects and want to update or add a property to the saved object.
Apparently it won't save the changes, any idea why?
NSManagedObjectContext *managedObjectContext = ((VentoAppDelegate*) [[UIApplication sharedApplication] delegate]).managedObjectContext;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:EntityNameString inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"Error - Events=nil - %#", [error localizedDescription]);
}
if ([objects count] > 0) {
for (NSManagedObject* object in objects) {
if (distance <= maxDistance) {
if (bla-bla-bla) {
[object setValue:[NSNumber numberWithBool:YES] forKey:#"notification"];
[self saveContext];
}
}
}
}
Thank you!
If you change managed object it is changed only in memory. You need to save managed context after changing anything. Add something like this:
NSError *error;
if (![object.managedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}

How to link existing values in a 1 to many relationship in core data?

I am trying to link a value that's already in category to the wod entity. Since I do want to call a new record for each record of wod for a category. Not sure how to do this. I was thinking of using predicate but I am not exactly sure how to link it from a fetch request.
this is what my schema looks like:
Here's the code that tries to link them together:
NSManagedObjectContext *context = [self managedObjectContext];
Wod *wodInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Wods"
inManagedObjectContext:context];
[wodInfo setValue:#"Frank" forKey:#"name"];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Categories"
inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:#"(name == %#", #"Time"]];
// This is the part where i am unsure, since i am not exactly sure how to link them up
Category *category = reques
wodInfo.category =
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
Any help would be greatly appreciated.
NSError *error = nil;
NSArray *categories = [context executeFetchRequest:request error:&error];
Category *category = [categories lastObject];
wodInfo.category = category;
Be careful about your call to [context save:&error]. You are passing the address of the error variable, which is not initialized in your code and will refer to a random address, which might lead to weird errors in your application. I would recommend setting it to nil before passing it to the save: method.

Core data storage is repeated

I am trying to use Core Data in my application and I have been succesful in storing data into the entity.The data storage is done in the applicationDidFinishLaunchingWithOptions() method.But when I run the app again,it again gets saved.So how do I check if the data is already present or not??
Here is the code(Saving):
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"FailedBankInfo"
inManagedObjectContext:context];
[failedBankInfo setValue:#"Test Bank" forKey:#"name"];
[failedBankInfo setValue:#"Testville" forKey:#"city"];
[failedBankInfo setValue:#"Testland" forKey:#"state"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
(Retrieving):-
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"FailedBankInfo" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(#"Name: %#", [info valueForKey:#"name"]);
}
`
Another thing I want to know that if I have thousands of records to store,then is there any other way to do it or can it be done through coding only???
Thanks
from what i understand you want to add all the data once only one time?
if so, move the inserting to the persistentStoreCoordinator method, and check if this is the first time the app lunches, by checking :
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path] isDirectory:NULL]) {
firstRun = YES;
}
if it does then load the data. if not do nothing. this is how it look's at the end :
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"your_app.sqlite"];
BOOL firstRun = NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path] isDirectory:NULL]) {
firstRun = YES;
}
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (firstRun) {
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"FailedBankInfo"
inManagedObjectContext:context];
[failedBankInfo setValue:#"Test Bank" forKey:#"name"];
[failedBankInfo setValue:#"Testville" forKey:#"city"];
[failedBankInfo setValue:#"Testland" forKey:#"state"];
NSError *error;
[moc save:&error];
}
return persistentStoreCoordinator_;
}
a.the way i do that is to create a plist with all the data.
b.import the plist as array of dictionaries (each dictionary is an entity".
c. set a function that iterates throw the array and adds the entities to the context.
something like that:
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"recordsList" ofType:#"plist"];
NSArray *recordsArray = [[NSArray alloc] initWithContentsOfFile:thePath];
for (int i=0;i<[recordsArray count];i++)
{
//add the objects to the context
}
}
I have tried to simplify the answer, but you should know there are alot of thing you can do to better the process.
good luck

Problem in fetching from core data to array

In my core date in the entity name called Event and in that there is an attribute called "name". I want to fetch all the values of term from coredata to an nsarray. I used the below code and it is not working. Anybody please helpp.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, #"Error fetching events: %#\n%#", [error localizedDescription], [error userInfo]);
NSMutableArray *namesArray = [[NSMutableArray alloc]init];
namesArray = [events valueForKey:#"name"];
Your code is close and should have worked even though you were leaking memory.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, #"Error fetching events: %#\n%#", [error localizedDescription], [error userInfo]);
//You were leaking your request here
[request release], request = nil;
//The following line is redundant. You are leaking an array here
//NSMutableArray *namesArray = [[NSMutableArray alloc]init];
NSArray *namesArray = [events valueForKey:#"name"];
At this point you should have an array of names which are NSString instances.
The next question is -- Why? Why do you need to pull them out into an array of strings when you already have the NSManagedObject instances? Why disconnect the data from the Core Data objects.