如何使用Core Data从数据库保存和检索数据?

时间:2014-04-19 05:34:44

标签: ios

我正在创建记录NSManagedObject类。并写下3个代码

 - (NSManagedObjectContext *) managedObjectContext
 - (NSManagedObjectModel *)managedObjectModel
 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator

  My Saving code is :
  Record *newentry = [NSEntityDescription insertNewObjectForEntityForName:@"Record" inManagedObjectContext:self.mManagedObjectContext];
    newentry.code = entryStr;

  But its not saving in database. Anybody can help me ?

1 个答案:

答案 0 :(得分:0)

在AppDelegate.h中

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

 @interface AppDelegate : UIResponder <UIApplicationDelegate>
 -(NSArray*)getAlldata:(NSString*)Code;

 @property (strong, nonatomic) UIWindow *window;
 @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
 @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
 @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator ;

 @end

 --------------------------------

AppDelegate.m

 #import "AppDelegate.h"
 @implementation AppDelegate
 @synthesize managedObjectContext = _managedObjectContext;
 @synthesize managedObjectModel = _managedObjectModel;
 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

 #pragma mark - core data part

 - (NSManagedObjectContext *) managedObjectContext
{
if (_managedObjectContext != nil)
{
    return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator: coordinator];
}

return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil)
{
    return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

return _managedObjectModel;
}

 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
 {
if (_persistentStoreCoordinator != nil)
{
    return _persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
                                           stringByAppendingPathComponent: @"sample.sqlite"]];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                               initWithManagedObjectModel:[self managedObjectModel]];
if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                              configuration:nil URL:storeUrl options:nil error:&error])
{
    /*Error for store creation should be handled in here*/
}

return _persistentStoreCoordinator;
}

- (NSString *)applicationDocumentsDirectory
{
   return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
-(NSArray*)getAlldata:(NSString*)Code
{
// initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

//Setting Entity to be Queried
NSEntityDescription *entity = [NSEntityDescription entityForName:Code
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError* error;

// Query on managedObjectContext With Generated fetchRequest
NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

// Returning Fetched Records
return fetchedRecords;
}

使用核心数据保存在数据库中的位置----

    in .h file write : @property(nonatomic ,strong)NSManagedObjectContext *mManagedObjectContext;
    // Save the Date in core data server..............

    Record *newentry = [NSEntityDescription insertNewObjectForEntityForName:@"Record" inManagedObjectContext:self.mManagedObjectContext];
    newentry.code = @"name";
    NSError *error;
    if ([self.mManagedObjectContext save:&error])
    {
        NSLog(@"save successfully");
    }
    else
    {
        NSLog(@"fail to save");
    }

你在哪里检索数据////

 #import "AppDelegate.h"
  AppDelegate *app = [UIApplication sharedApplication].delegate;
  self.CodeHistory_Arr = [app getAllCaptchaCode:@"Record"];
  for (int i = 0; i < [self.CodeHistory_Arr count]; i++)
  {
    Record *lorecord = [self.CodeHistory_Arr objectAtIndex:i];
    NSLog(@"%@",lorecord.code);
  }
  • 不要忘记添加CoreData.Framework