Insert values in multiple entity core data - iphone

I'm trying to insert values in 2 entities. It is possible if I use 2 NSManagedObject, each one set for a different entity, but I was wondering if there's another way to do it - a more elegant way.
Right now I'm doing something like this:
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entity" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:[NSDate date] forKey:#"Date"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
NSEntityDescription *entity2 = [NSEntityDescription entityForName:#"Entity2" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *newManagedObject2 = [NSEntityDescription insertNewObjectForEntityForName:[entity2 name] inManagedObjectContext:context];
[newManagedObject2 setValue:[NSDate date] forKey:#"Date"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
It works, but I'm not convinced that it is the best way.

Related

NSFetchRequest not fetching chat messages in proper order

I am implementing a chat database using core data in iphone. I have created two entity chatuser and chatmessage. and there is one to many relationship between chatuser and chatmessgae entity. For one chatuser there can be many chatmessages. I am storing data like
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Chatuser"
inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"chatuser == %#", chatuser];
[request setPredicate:pred];
NSArray *userArray=[self.managedObjectContext executeFetchRequest:request error:&error];
if ([userArray count] > 0){
Chatuser *user = [userArray objectAtIndex:0];
Chatmessage *message = [NSEntityDescription insertNewObjectForEntityForName:#"Chatmessage" inManagedObjectContext:self.managedObjectContext];
message.chatmessage = chatmessage;
[user addAllchatmessagesObject:message];
NSError *error;
if(![self.managedObjectContext save:&error])
{
NSLog(#"whoops, couldn't save: %#", [error localizedDescription]);
}
}
// }
else
{
Chatuser *user = [NSEntityDescription insertNewObjectForEntityForName:#"Chatuser" inManagedObjectContext:self.managedObjectContext];
user.chatuser = chatUser;
Chatmessage *message = [NSEntityDescription insertNewObjectForEntityForName:#"Chatmessage" inManagedObjectContext:self.managedObjectContext];
message.chatmessage = chatmessage;
[user addAllchatmessagesObject:message];
NSError *error;
if(![self.managedObjectContext save:&error])
{
NSLog(#"whoops, couldn't save: %#", [error localizedDescription]);
}
}
and fetching data this way
managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Chatuser" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSError *error;
NSPredicate *pred = [NSPredicate predicateWithFormat:#"chatuser == %#", appDelegate.chatUser];
[request setPredicate:pred];
NSArray *userinfo = [self.managedObjectContext executeFetchRequest:request error:&error];
if([userinfo count]>0)
{
Chatuser *user = [userinfo objectAtIndex:0];
NSSet *messageset = user.allchatmessages;
self.messageinfo = [messageset allObjects];
int message_count=[self.messageinfo count];
NSLog(#"Message count : %d", message_count);
for(int i=(message_count-1);i>=0;i--)
{
Chatmessage *chatmsgnew = [self.messageinfo objectAtIndex:i];
[tableArray addObject:chatmsgnew.chatmessage];
}
}
now the problem is that chat messages is not coming in the order in which i am storing them. Like i am storing messages 1,2,3,4. and while fetching its coming like 2,1,4,3.....
I am not getting the problem. Can anybody suggest anything.
A fetch request does not necessarily return the objects in the order they were inserted into the database. If you need a specific order, you have to add an Integer attribute (e.g. messageId) to the entity, and add a sort descriptor to the fetch request:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"messageId"
ascending:YES];
[request setSortDescriptors:#[sort]];
Added: The above method works if you fetch Chatmessage objects. So instead of fetching a Chatuser first, you could create a fetch request for the Chatmessage entity, with a predicate like
[NSPredicate predicateWithFormat:#"user.chatuser == %#", appDelegate.chatUser]
(assuming that "user" is the inverse relationship from Chatmessage to Chatuser), and the above sort descriptor.
Alternatively, if you have a Chatuser object, then you can sort user.allchatmessages like this:
NSSet *messageset = user.allchatmessages;
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"messageId"
ascending:YES];
self.messageinfo = [[messageset allObjects] sortedArrayUsingDescriptors:#[sort]];

iOS Core Data: distinguish multiple objects in Transformable attribute

I am trying to implement simple Core Data class to store and retrieve different Language strings(array) downloaded from the server. So far I have created created Core Data template in App Delegate, created data model with one Entity "MyArray" and one Attribute "language", and written following sample code to store and retrieve these arrays. Now as both the strings arrays stored in same attribute "language", how I can retrieve Chinese language array?
// Fetch arrays code
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"MyArray" inManagedObjectContext:context];
[request setEntity:entity];
NSArray *results = [context executeFetchRequest:request error:nil];
for (NSManagedObject *object in results) {
NSArray *a = [object valueForKey:#"language"];
// Use array
}
-(void)storeEnglishStrings {
NSArray *array = [[NSArray alloc] initWithObjects:#"str1",#"str2", #"str3", #"str4", #"str5", nil];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[object setValue:array forKey:#"language"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
-(void)storeChineseStrings {
NSArray *array = [[NSArray alloc] initWithObjects:#"串1",#"串2", #"串3", #"串4", #"串5", nil];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[object setValue:array forKey:#"language"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
Check out the Core Data programming guide. You will need to use an NSFetchRequest
with a predicate for the chinese language. You need to make sure you can identify which one is the language of the record you are saving. I do not see the structure of your entity but I do see you are not saving the language. Also, you should reconsider your model. You usually should not need to save an NSArray into core data. You can, but it usually means your model is lacking better design.

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.

Insert values in relationship field

Im trying to insert values in a core data entity, but when I try to insert in a Relationship field it crash
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName: [entity name] inManagedObjectContext:context];
[newManagedObject setValue:[NSDate date] forKey:#"fechaAprovacion"];
[newManagedObject setValue:[NSDate date] forKey:#"fechaUltimoOficio"];
//relationship field----->[newManagedObject setValue:[NSNumber numberWithInteger:self.index.row] forKey:#"vObra"]; //<---relationship field
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
I solve it!! i just have to insert the NSManagedObject that is related some thing like this
NSManagedObject *reporteManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Reporte" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *partidaManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Avance" inManagedObjectContext:self.managedObjectContext];
[partidaManagedObject setValue:reporteManagedObject forKey:#"avanceReporte"];

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
}