如何将 Core Data 包含到 Xcode 中已创建的 iOS 项目中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10227604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:01:34  来源:igfitidea点击:

How can I include Core Data to an already created iOS project in Xcode?

iphoneobjective-cxcodecore-data

提问by user1300511

I forgot to include Core Data, and now I've completed half of the project and want to include it now.

我忘了包含 Core Data,现在我已经完成了一半的项目,现在想包含它。

Is it possible to include Core Data now? If so can anyone tell me how to do that?

现在可以包含核心数据吗?如果是这样,谁能告诉我该怎么做?

回答by hp iOS Coder

Xcode 4.3.2 To add core-data framework.

Xcode 4.3.2 添加核心数据框架。

Select Target->Summary Pane-> Linked Frameworks & Libraries.

选择目标-> 摘要窗格-> 链接的框架和库。

enter image description here

在此处输入图片说明

In ABOVE image CoreData Framework is already added. U can click on '+' button below it to add frameworks of ur choice.

在上图中已经添加了 CoreData 框架。你可以点击它下面的“+”按钮来添加你选择的框架。

ONCE U CICK ON '+' BUTTON U'LL SEE BELOW IMAGE SCREEN.

一旦你点击“+”按钮,你就会看到下面的图像屏幕。

enter image description here

在此处输入图片说明

To add new files to it go to File-> New File -> iOS tab-> CoreData setion.You can file of ur choice

要向其中添加新文件,请转到 File-> New File -> iOS tab-> CoreData setion.You 可以选择文件

enter image description here

在此处输入图片说明

回答by Eugene

Add CoreData framework to the project, then create a .xdatamodeld file (File->New->CoreData-> Data Model). Name it DataModel. Then create a singleton class that will handle all data persistence operations:

将 CoreData 框架添加到项目中,然后创建一个 .xdatamodeld 文件(File->New->CoreData-> Data Model)。将其命名为数据模型。然后创建一个处理所有数据持久化操作的单例类:

.h

。H

    //
    //  DataAccessLayer.h
    //  
    //
    //  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
    //

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

    @interface DataAccessLayer : NSObject

    @property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
    @property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
    @property (strong, nonatomic) NSPersistentStoreCoordinator *storeCoordinator;

    + (DataAccessLayer *)sharedInstance;
    - (void)saveContext;

    @end

.m

.m

//
//  DataAccessLayer.m
//  
//
//  Created by admin on 2/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DataAccessLayer.h"
@interface DataAccessLayer ()
- (NSURL *)applicationDocumentsDirectory;
@end

@implementation DataAccessLayer
@synthesize storeCoordinator;
@synthesize managedObjectModel;
@synthesize managedObjectContext;

+ (DataAccessLayer *)sharedInstance {
  __strong static DataAccessLayer *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[DataAccessLayer alloc] init];
    sharedInstance.storeCoordinator = [sharedInstance persistentStoreCoordinator];
    sharedInstance.managedObjectContext = [sharedInstance managedObjectContext];
  });
  return sharedInstance;
}

#pragma mark - Core Data

- (void)saveContext {
  NSError *error = nil;
  if (managedObjectContext != nil)
  {
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
    {
      NSLog(@"error: %@", error.userInfo);
      /*
       Replace this implementation with code to handle the error appropriately.

       abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
       */
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!"
                                                      message:@"Something has gone terribly wrong! You need to reinstall the app in order for it to work properly."
                                                     delegate:nil
                                            cancelButtonTitle:@"Close."
                                            otherButtonTitles:nil, nil];
      [alert show];
    } 
  }
}

#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {
  if (managedObjectContext != nil)
  {
    return managedObjectContext;
  }

  if (storeCoordinator != nil)
  {
    self.managedObjectContext = [[NSManagedObjectContext alloc] init];
    [managedObjectContext setPersistentStoreCoordinator:storeCoordinator];
  }
  return managedObjectContext;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel {
  if (managedObjectModel != nil)
  {
    return managedObjectModel;
  }
  NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DataModel" withExtension:@"momd"];
  self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  return managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  if (storeCoordinator != nil)
  {
    return storeCoordinator;
  }

  NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"model.sqlite"];

  NSError *error = nil;
  self.storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  if (![storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
  {
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

     Typical reasons for an error here include:
     * The persistent store is not accessible;
     * The schema for the persistent store is incompatible with current managed object model.
     Check the error message to determine what the actual problem was.


     If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

     If you encounter schema incompatibility errors during development, you can reduce their frequency by:
     * Simply deleting the existing store:
     [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

     * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
     [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

     Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!"
                                                    message:@"Something has gone terribly wrong! You need to reinstall the app in order for it to work properly."
                                                   delegate:nil
                                          cancelButtonTitle:@"Close."
                                          otherButtonTitles:nil, nil];
    [alert show];
  }    

  return storeCoordinator;
}

#pragma mark Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory {
  return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


@end

回答by stefan bund

Both the hp iOS Coder's and Eugene's answers are correct!

无论是惠普的iOS编码器的和尤金的答案是正确的!

A Core Data file (or project) is configured to:

核心数据文件(或项目)被配置为:

  1. link to and include the core data framework (and does so as an import statement in your project's .pchfile)
  2. the app delegate header (.h) includes properties declaring a context, modeland coordinator(as above)
  3. the app delegate's .m defines saveContext, managedObjectContext, managedObjectModel, persistentStoreCoordinator, applicationDocumentDirectoryfunctions/methods
  4. a data model, as above
  1. 链接并包含核心数据框架(并作为项目.pch文件中的导入语句执行此操作)
  2. 应用程序委托头(.h)包括属性声明一个contextmodelcoordinator(如上)
  3. 所述app delegate的.M定义saveContextmanagedObjectContextmanagedObjectModelpersistentStoreCoordinatorapplicationDocumentDirectory的功能/方法
  4. 数据模型,如上