How to get all records From CoreData Base using NSManagedObjectSubClass?

Musthafa picture Musthafa · Apr 24, 2012 · Viewed 29.8k times · Source

I am trying to implement CoreData in ios Application,Now I want to Fetch all records from Entity MUSTHAFA

  My  NSManagedObjectedSubClass is MUSTAHFA

MUSTHAFA.m

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface MUSTHAFA : NSManagedObject {
@private
}
@property (nonatomic, retain) NSString * FirstName;
@property (nonatomic, retain) NSNumber * Age;
@property (nonatomic, retain) NSString * Location;
@property (nonatomic, retain) NSString * LastName;

@end

#import "MUSTHAFA.h"


@implementation MUSTHAFA
@dynamic FirstName;
@dynamic Age;
@dynamic Location;
@dynamic LastName;

@end

Adding Records to Core Data

-(void)AddRecordToCoreData{

    //NSLog(@"______ ADD Core Data Implementaion");  
    MUSTHAFA *event = (MUSTHAFA *)[NSEntityDescription insertNewObjectForEntityForName:@"MUSTHAFA" inManagedObjectContext:managedObjectContext];
    [event setLastName:@"JOHN"];
    [event setFirstName:@"JOSE "];
    [event setLocation:@"IDUKKI "];
    [event setAge:[NSNumber numberWithInt:25]];    
    NSError *error;
    if (![managedObjectContext save:&error]) 
        {       
        NSLog(@"Error..%@",error);
    }
       else
       {
        NSLog(@"Data added to MUSTHAFA ");
       }      
}

Retrieving all Values from Core Data just like select * from dbTable;

-(void)FetchRecordFromCoreData:(id)data1{

     //NSLog(@"______ Fetch Core Data Implementaion");  
    MUSTHAFA *event = (MUSTHAFA *)[NSEntityDescription insertNewObjectForEntityForName:@"MUSTHAFA" inManagedObjectContext:managedObjectContext];

   //USING event how can fetch all record from Data base;


}

USING event (Instance of MUSTAHFA) how can fetch all record from Data base?

Answer

Joseph DeCarlo picture Joseph DeCarlo · Apr 24, 2012
NSManagedObjectContext *context = //Get it from AppDelegate

NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"MUSTHAFA"];

NSError *error = nil;

NSArray *results = [context executeFetchRequest:request error:&error];

if (error != nil) {

   //Deal with failure
}
else {

   //Deal with success
}

[request release];