Thursday, 7 March 2013

How to retrieve or fetch data from CORE DATA in iOS for a particular entity.

NSManagedObjectContext *context = [[SharedVars sharedInstance]localContext];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];

// Condition to check for form id and instance
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"formId == %i && instanceNo == %d", [form.formId intValue],instancevalue];
    [request setPredicate:predicate];
//   NSPredicate for queries 

NSEntityDescription *entity = [NSEntityDescription entityForName:@"UnsavedForm" inManagedObjectContext:context];
[request setEntity:entity];
// Order   by   questionId.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"questionId" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
//   NSSortDescriptor for sorting purpose

NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil)
// Handle the error.
//mutableFetchResults contains the core data elements , you can handle as per your //requirement as i am doing for my specific requirement below.
NSMutableArray *Qsetter=[[NSMutableArray alloc]init];
NSMutableArray *Asetter=[[NSMutableArray alloc]init];
    for(int objCount=0;objCount<[mutableFetchResults count];objCount++)
   YourEntityClass=[mutableFetchResults objectAtIndex:objCount];
     //   NSLog(@" form id : %@ question id : %@ answers : %@ instance No ; %@",unsavedform.formId,unsavedform.questionId,unsavedform.answers,unsavedform.instanceNo);
        [Qsetter addObject:unsavedform.questionId];
        [Asetter addObject:unsavedform.answers];