In my project I'm entering the same objects in two different Entities in the same data model with same MOC and Persistence Store. I don't want to duplicate the entity because I'm going to modify (remove) objects from the first entity. My question is How I'm going to fetch the objects form another entity? DO I need to have different persistence store and MOC? Well I already fetched the objects but its giving me null value and crashed telling that object can not be nil value.
I guess values are not saving in the core data. Following is the line of code I used to store the values in coreData
CommonEvent *commonEvent = (CommonEvent *)[NSEntityDescription insertNewObjectForEntityForName:@"CommonEvent" inManagedObjectContext:_managedObjectContext];
[commonEvent setValue:number forKey:@"commonNumber"];
[commonEvent setValue:name forKey:@"commonName"];
following is the line of code to fetch the data form core data
CommonEvent *event;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"CommonEvent" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// define a sort descriptor
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc]initWithKey:@"commonName" ascending:YES];
NSSortDescriptor *numberDescriptor = [[NSSortDescriptor alloc]initWithKey:@"commonNumber" ascending:YES];
NSArray *scArray = [[NSArray alloc]initWithObjects:nameDescriptor,numberDescriptor, nil];
// give sort descriptor array to the fetch request
fetchRequest.sortDescriptors = scArray;
// fetch all objects
NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(@" we have a problem: %@", error);
}
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
NSLog(@" %@ %@ for index:%d", [event.commonNumber description],[event.commonName description], indexPath.row); // It shows that object values are null
// display all objects
for (CommonEvent *event in fetchedObjects) {
[mutableArray addObject:[event.commonNumber description]];
//
NSLog(@" %@ %@ for index:%d", [event.commonNumber description],[event.commonName description], indexPath.row);
}