如何使用NSManagedObjectSubClass从CoreData Base获取所有记录?

时间:2012-04-24 12:10:25

标签: objective-c ios core-data nsmanagedobject nsmanagedobjectcontext

我正在尝试在CoreData应用中实施ios,现在我想从实体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

将记录添加到核心数据

-(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 ");
       }      
}

从核心数据中检索所有值,就像从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事件(MUSTAHFA的实例)如何从数据库中获取所有记录?

2 个答案:

答案 0 :(得分:29)

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];

答案 1 :(得分:9)

AppDelegate *delegate = [UIApplication sharedApplication].delegate;

NSManagedObjectContext *context =[delegate managedObjectContext];

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

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

ChannelDBArray=[[NSMutableArray alloc]init];

for (NSManagedObject *obj in results) {


    NSArray *keys = [[[obj entity] attributesByName] allKeys];
    NSDictionary *dictionary = [obj dictionaryWithValuesForKeys:keys];

}
if (error != nil) {

    //Deal with failure
}
else {

    //Deal with success
}