ios 将核心数据添加到现有的 iPhone 项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2032818/
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-08-30 16:46:32  来源:igfitidea点击:

Adding Core Data to existing iPhone project

ioscore-data

提问by swalkner

I'd like to add core data to an existing iPhone project, but I still get a lot of compile errors:

我想将核心数据添加到现有的 iPhone 项目中,但我仍然遇到很多编译错误:

- NSManagedObjectContext undeclared

 - Expected specifier-qualifier-list before 'NSManagedObjectModel'

 - ...

I already added the Core Data Framework to the target (right click on my project under "Targets", "Add" - "Existing Frameworks", "CoreData.framework").

我已经将核心数据框架添加到目标(右键单击“目标”、“添加”-“现有框架”、“CoreData.framework”下的我的项目)。

My header-file:

我的头文件:

NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;       
NSPersistentStoreCoordinator *persistentStoreCoordinator;

[...]

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

What am I missing? Starting a new project is not an option...

我错过了什么?开始一个新项目不是一种选择......

Thanks a lot!

非常感谢!

editsorry, I do have those implementations... but it seems like the Library is missing... the implementation methods are full with compile error like "managedObjectContext undeclared", "NSPersistentStoreCoordinator undeclared", but also with "Expected ')' before NSManagedObjectContext" (although it seems like the parenthesis are correct)...

编辑抱歉,我确实有这些实现......但似乎库丢失了......实现方法充满了编译错误,如“ managedObjectContext undeclared”,“ NSPersistentStoreCoordinator undeclared”,但也有“预期的')'之前NSManagedObjectContext”(尽管它似乎括号是正确的)...

#pragma mark -
#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;
    }

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


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in    
 application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    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 (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] 
        stringByAppendingPathComponent: @"Core_Data.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] 
    initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator 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.
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}    

return persistentStoreCoordinator;
}

回答by Joost

All the CoreData header files are imported in App_Prefix.pch, so the CoreData classes will be available throughout your Project, so you don't have to manually import the header in the files you need them.

所有 CoreData 头文件都导入到 中App_Prefix.pch,因此 CoreData 类将在整个项目中可用,因此您不必在需要它们的文件中手动导入头文件。

So open up Xcode and look for some file like App_Prefix.pch, by default it's in the Other Sourcesgroup. After the UIKitimport statement, add the following line:

因此,打开 Xcode 并查找类似 的文件App_Prefix.pch,默认情况下它在Other Sources组中。在UIKitimport 语句之后,添加以下行:

#import <CoreData/CoreData.h>

And you should be ready to go.

你应该准备好了。

Xcode 4

Xcode 4

For projects created in Xcode 4, the prefix file can be found in the Supporting Filesgroup in the Project navigator. It's called 'projectname-Prefix.pch' by default.

对于在 Xcode 4 中创建的项目,可以Supporting Files在项目导航器的组中找到前缀文件。默认情况下,它称为“ projectname-Prefix.pch”。

Xcode 6+

Xcode 6+

Starting with Xcode 6, the precompiled header file is no longer included by default. This is because of the introduction of Modules, which take away the need to use precompiled headers.While it is still possible to manually add a PCH file to globally include the CoreData headers, consider specifying the CoreData dependency using @import CoreData;* in every file that uses CoreData. This makes dependencies explicit and more importantly will avoid this question's problem in the future.

从 Xcode 6 开始,默认情况下不再包含预编译头文件。这是因为引入了模块,它消除了使用预编译头文件的需要。虽然仍然可以手动添加 PCH 文件以全局包含 CoreData 标头,但请考虑@import CoreData;在每个使用 CoreData 的文件中使用 *指定 CoreData 依赖项。这使得依赖关系明确,更重要的是将来会避免这个问题的问题。

* Modules need to be enabledfor this to work.

* 模块需要启用才能工作。

回答by ColossalChris

Just to expound on all the steps you actually need to perform to add Core Data to a project that previously did not have it:

只是为了说明将 Core Data 添加到以前没有它的项目中实际需要执行的所有步骤:

Step 1: Add the Framework

步骤 1:添加框架

Click on your app target (on the left pane its the top icon with the name of your app) then go to the 'Build Phases' tab then on 'Link Binary With Libraries', click the little '+' at the bottom then find 'CoreData.framework' and add it to your project

单击您的应用程序目标(在左侧窗格中带有您的应用程序名称的顶部图标),然后转到“构建阶段”选项卡,然后单击“将二进制文件与库链接”,单击底部的小“+”,然后找到'CoreData.framework' 并将其添加到您的项目中

Then either import coredata on all the objects you need it (the non-sexy way) using:

然后使用以下方法在您需要的所有对象上导入 coredata(非性感方式):

Swift

迅速

import CoreData

Objective C

目标 C

#import <CoreData/CoreData.h>

or add the import below the common imports in your .pch file (much more sexy) like this:

或在 .pch 文件中的常见导入下方添加导入(更性感),如下所示:

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif

Step 2: Add the Data Model

步骤 2:添加数据模型

To add the .xcdatamodel file right click/control-click on your files in the right pane (like in a Resources folder for safe keeping) and select to Add a New File, Click the Core Data tab when selecting your file type then Click 'Data Model', give it a name and click Next and Finish and it will add it to your project. When you click on this Model object you will see the interface to add the Entities to your project with any relationships you want.

要添加 .xcdatamodel 文件,请右键单击/控制单击右侧窗格中的文件(例如在资源文件夹中以确保安全)并选择添加新文件,在选择文件类型时单击核心数据选项卡,然后单击“数据模型”,为其命名并单击“下一步”和“完成”,它会将其添加到您的项目中。当您单击此模型对象时,您将看到用于将实体添加到您的项目中的界面,您可以使用任何您想要的关系。

Step 3: Update App Delegate

第 3 步:更新 App Delegate

In Swifton AppDelegate.swift

在AppDelegate.swift 上的Swift

//replace the previous version of applicationWillTerminate with this
func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
}

func saveContext () {
    var error: NSError? = nil
    let managedObjectContext = self.managedObjectContext
    if managedObjectContext != nil {
        if managedObjectContext.hasChanges && !managedObjectContext.save(&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.
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }
    }
}

// #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.
var managedObjectContext: NSManagedObjectContext {
    if !_managedObjectContext {
        let coordinator = self.persistentStoreCoordinator
        if coordinator != nil {
            _managedObjectContext = NSManagedObjectContext()
            _managedObjectContext!.persistentStoreCoordinator = coordinator
        }
    }
    return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
    if !_managedObjectModel {
        let modelURL = NSBundle.mainBundle().URLForResource("iOSSwiftOpenGLCamera", withExtension: "momd")
        _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
    }
    return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil

// 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.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
    if !_persistentStoreCoordinator {
        let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("iOSSwiftOpenGLCamera.sqlite")
        var error: NSError? = nil
        _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
            /*
            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.
            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:
            [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
            Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
            */
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }
    }
    return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil

// #pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.endIndex-1] as NSURL
}

In Objective Cmake sure to add these objects to AppDelegate.h

Objective C 中确保将这些对象添加到 AppDelegate.h

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

 - (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data

Synthesize the previous objects in AppDelegate.m like this:

像这样合成 AppDelegate.m 中的先前对象:

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

Then add these methods to AppDelegate.m (make sure to put the name of the model that you added in the spots shown):

然后将这些方法添加到 AppDelegate.m(确保将您添加的模型的名称放在显示的位置):

- (void)saveContext{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

- (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;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"NAMEOFYOURMODELHERE" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

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

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

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

Step 4: Get the Data Objects to the ViewControllers Where You Need the Data

第 4 步:将数据对象获取到需要数据的 ViewControllers

Option 1. Use the App Delegate's ManagedObjectContext from VC (Preferred and Easier)

选项 1. 使用来自 VC 的 App Delegate 的 ManagedObjectContext(首选且更简单)

As suggeted by @brass-kazoo - Retrieve a reference to AppDelegate and its managedObjectContext via:

正如@brass-kazoo 所建议的那样 - 通过以下方式检索对 AppDelegate 及其 managedObjectContext 的引用:

Swift

迅速

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
 appDelegate.managedObjectContext

Objective C

目标 C

 [[[UIApplication sharedApplication] delegate] managedObjectContext];

in your ViewController

在你的 ViewController

Option 2. Create ManagedObjectContext in your VC and have it match AppDelegate's from the AppDelegate (Original)

选项 2. 在您的 VC 中创建 ManagedObjectContext 并使其与 AppDelegate(原始)中的 AppDelegate 相匹配

Only showing old version for Objective C since much easier to use the preferred method

仅显示 Objective C 的旧版本,因为使用首选方法要容易得多

in the ViewController.h

在 ViewController.h

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

In the ViewController.m

在 ViewController.m 中

@synthesize managedObjectContext = _managedObjectContext;

In the AppDelegate, or class where the ViewController is created set the managedObjectContext to be the same as the AppDelegate one

在 AppDelegate 或创建 ViewController 的类中,将 managedObjectContext 设置为与 AppDelegate 相同

ViewController.managedObjectContext = self.managedObjectContext;

If you want the viewcontroller using Core Data to be a FetchedResultsController then you'll need to make sure this stuff is in your ViewController.h

如果您希望使用 Core Data 的视图控制器成为 FetchedResultsController 那么您需要确保这些东西在您的 ViewController.h 中

@interface ViewController : UIViewController <NSFetchedResultsControllerDelegate> {
  NSFetchedResultsController *fetchedResultsController;
  NSManagedObjectContext *managedObjectContext;
}

 @property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

And this is in ViewController.m

这是在 ViewController.m

@synthesize fetchedResultsController, managedObjectContext;

After all of that you can now use this managedObjectContext to run all the usual fetchRequests needed for CoreData goodness! Enjoy

毕竟,您现在可以使用这个 managedObjectContext 来运行 CoreData 所需的所有常用 fetchRequests !享受

回答by kurrodu

For Swift 3: INCLUDES SAVING AND RETRIEVING DATA

对于 Swift 3:包括保存和检索数据

Step 1: Add Framework

第 1 步:添加框架

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

Step 2:Add Data model

第 2 步:添加数据模型

File > New > File > Core Data > Data Model

文件 > 新建 > 文件 > 核心数据 > 数据模型

  • Name the file as SampleDatathe resultant file would be SampleData.xcdatamocelId
  • 将文件命名为SampleData结果文件将是SampleData.xcdatamocelId

Step 3:Add the below functions to your App Delegate and add "import CoreData" to the top

第 3 步:将以下函数添加到您的 App Delegate 并在顶部添加“import CoreData”

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
}


// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */


    // SEE BELOW LINE OF CODE WHERE THE 'name' IS SET AS THE FILE NAME (SampleData) FOR THE CONTAINER

    let container = NSPersistentContainer(name: "SampleData")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

STEP 4:Adding Entity and Attribute to the Model

第 4向模型添加实体和属性

a) Add Entity enter image description here

a) 添加实体 在此处输入图片说明

b) Add Attribute enter image description here

b) 添加属性 在此处输入图片说明

STEP 5:Saving Data

步骤 5:保存数据

func saveItem(itemToSave: String){
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

//**Note:** Here we are providing the entityName **`Entity`** that we have added in the model
    let entity = NSEntityDescription.entity(forEntityName: "Entity", in: context)
    let myItem = NSManagedObject(entity: entity!, insertInto: context)

    myItem.setValue(itemToSave, forKey: "item")
    do {
        try context.save()
    }
    catch{
        print("There was an error in saving data")
    }
}

STEP 5:Retrieving Data

第 5检索数据

override func viewWillAppear(_ animated: Bool) {
    // Obtaining data from model
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")

    do {
        let results = try context.fetch(fetchRequest)
        let obtainedResults = results as! [NSManagedObject]
        let firstResult = obtainedResults[0]
        let myValue = firstResult.value(forKey: "item")

        print("myValue: \(myValue)")
    } catch {
        print("Error")
    }
}

回答by Eimantas

Try creating Core Data backed Cocoa application and look at AppDelegate. You'll see core data stack implementation methods there as well as managed object model file for defining your entities and other core-data releated stuff.

尝试创建 Core Data 支持的 Cocoa 应用程序并查看 AppDelegate。您将在那里看到核心数据堆栈实现方法以及用于定义实体和其他核心数据相关内容的托管对象模型文件。

You've shown us only header (i.e. declaration), but not implementation (i.e. definition) of the Core Data stack.

您只向我们展示了头文件(即声明),而不是核心数据堆栈的实现(即定义)。

回答by Jay Greene

If you run into this same issue in xcode 4, as I did. It is different: I had to select the project, then in targets expand "Link Binary With Libraries"which shows the current libraries. From there click the + (plus sign) to select any additional libraries you need. I placed it in the top of the project and had to move it (drag and drop) to the Frameworks Group, but that was it.

如果您像我一样在 xcode 4 中遇到同样的问题。它是不同的:我必须选择项目,然后在目标中展开“Link Binary With Libraries”,它显示了当前的库。从那里单击 +(加号)以选择您需要的任何其他库。我把它放在项目的顶部,不得不将它移动(拖放)到Frameworks Group,但就是这样。

回答by Henrik P. Hessel

As Eimantas stated your missing the implementiation of the Core Stack, like

正如 Eimantas 所说,您缺少核心堆栈的实现,例如

- (NSManagedObjectContext *) managedObjectContext;
- (NSManagedObjectModel *)managedObjectMode;
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator;

On solution would be to create a new core data driver project and copy / paste the implementation to your project.

解决方案是创建一个新的核心数据驱动程序项目并将实现复制/粘贴到您的项目中。

回答by Taichi Kato

For Swift 3:

对于 Swift 3:

File->new file->CoreData->Model to create a model.

File->new file->CoreData->Model 创建模型。

Refer to this linkfor more information on how to implement it.

有关如何实施它的更多信息,请参阅此链接

回答by Meera Raveendran

//in Swift 2.2 , you may do the following without changing the AppDelegate file.

//在 Swift 2.2 中,您可以在不更改 AppDelegate 文件的情况下执行以下操作。

  1. Project->targets-->linked frameworks and libraries Now add a new framework (click on +) 'CoreData'
  2. File->new file->CoreData->DataModel name it as say A.xcdatamodelid
  3. In A.xcdatamodelid create new enitity (click on entity+) name it as say Bc and set its class as 'Bc' in inspector window on right.
  4. Now Add attributes to the entity (click on attributes +) , add one attribute for eg : name and its type as String.
  5. Now editor->create NSManagedObject Subclass -->click next on the pop up window-->again next-->then click create. Two new files will be created 1. a new class named Bc.swift and an extension named Bc+coredataproperties.swift.
  6. File->new file->ios->cocoa Touch class-->set its subclass as NSObject->name it as DataController.swift Inside the file include ///

    import UIKit import CoreData class DataController: NSObject {

    var managedObjectContext: NSManagedObjectContext
    
    override  init() {
        // This resource is the same name as your xcdatamodeld contained in your project.
        guard let modelURL = NSBundle.mainBundle().URLForResource("A", withExtension:"momd") else {
            fatalError("Error loading model from bundle")
        }
        // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
        guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }
        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
        self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        self.managedObjectContext.persistentStoreCoordinator = psc
    
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let docURL = urls[urls.endIndex-1]
        /* The directory the application uses to store the Core Data store file.
        This code uses a file named "A.sqlite" in the application's documents directory.
        */
        let storeURL = docURL.URLByAppendingPathComponent("A.sqlite")
        do {
            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
        } catch {
            fatalError("Error migrating store: \(error)")
        }
    
    }
    

    }

  1. 项目->目标-->链接的框架和库现在添加一个新框架(点击+)'CoreData'
  2. File->new file->CoreData->DataModel 将其命名为 A.xcdatamodelid
  3. 在 A.xcdatamodelid 中创建新实体(单击实体+),将其命名为 Bc,并在右侧的检查器窗口中将其类设置为“Bc”。
  4. 现在向实体添加属性(单击属性 +),添加一个属性,例如:名称及其类型为字符串。
  5. 现在编辑器->创建NSManagedObject子类-->在弹出的窗口点击下一步-->再次下一步-->然后点击创建。将创建两个新文件 1. 一个名为 Bc.swift 的新类和一个名为 Bc+coredataproperties.swift 的扩展。
  6. File->new file->ios->cocoa Touch class-->将其子类设置为NSObject->将其命名为DataController.swift 文件内包含 ///

    导入 UIKit 导入 CoreData 类数据控制器:NSObject {

    var managedObjectContext: NSManagedObjectContext
    
    override  init() {
        // This resource is the same name as your xcdatamodeld contained in your project.
        guard let modelURL = NSBundle.mainBundle().URLForResource("A", withExtension:"momd") else {
            fatalError("Error loading model from bundle")
        }
        // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
        guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }
        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
        self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        self.managedObjectContext.persistentStoreCoordinator = psc
    
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let docURL = urls[urls.endIndex-1]
        /* The directory the application uses to store the Core Data store file.
        This code uses a file named "A.sqlite" in the application's documents directory.
        */
        let storeURL = docURL.URLByAppendingPathComponent("A.sqlite")
        do {
            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
        } catch {
            fatalError("Error migrating store: \(error)")
        }
    
    }
    

    }

//////

//////

  1. Now inside the viewcontroller file you can access your db using two methods. Important : include the statement in your viewController "import CoreData" a. call seed() -->to insert value into db/entity b. call fetch()--> to fetch value from db/entity
  1. 现在在 viewcontroller 文件中,您可以使用两种方法访问您的数据库。重要提示:在您的 viewController 中包含语句“import CoreData” 调用 seed() --> 将值插入 db/entity b。调用 fetch()--> 从 db/entity 中获取值

///////seed()-->def

///////种子()-->定义

func seedPerson() {

        // create an instance of our managedObjectContext
        let moc = DataController().managedObjectContext

        // we set up our entity by selecting the entity and context that we're targeting
        let entity = NSEntityDescription.insertNewObjectForEntityForName("Bc", inManagedObjectContext: moc) as! Bc

        // add our data
        entity.setValue("Meera", forKey: "name")


        // we save our entity
        do {
            try moc.save()
        } catch {
            fatalError("Failure to save context: \(error)")
        }
    }

//fetch() def

//fetch() def

func fetch() {
        let moc = DataController().managedObjectContext
        let personFetch = NSFetchRequest(entityName: "Bc")

        do {
            let fetchedPerson = try moc.executeFetchRequest(personFetch) as! [Bc]
            print(fetchedPerson.first!.name!)

        } catch {
            fatalError("Failed to fetch person: \(error)")
        }
    }

回答by Amannnn

 let alert  = UIAlertController(title:"Error", message: "No Internet Connection", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in}))
            alert.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { (action) in
                self.networkCall(text: self.daySelected)
            }))
            self.present(alert, animated: false, completion: nil)

回答by Slimshady

+(void) insetPlusUpdate:(NSDictionary *)dataa {

    NSManagedObjectContext * context;

    if (![[NSThread currentThread] isMainThread]) {

        context = [[NSManagedObjectContext alloc] init];

        [context setPersistentStoreCoordinator:[APP_DELEGATE persistentStoreCoordinator]];
    } else {

        context = [APP_DELEGATE managedObjectContext];
    }

    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:context];

    [request setEntity:entity];

    NSPredicate * check = [NSPredicate predicateWithFormat:@"attribute == %@", Dict[@"key"]];

    [request setPredicate:check];

    NSError * error = nil;

    if ([context countForFetchRequest:request error:&error] == 0) {

Entity.attribute = @"";

    } else {


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

        EntityName * entity = [array firstObject];

  Entity.attribute = @"";

    }

}

+(NSString *)fetch:(NSString *)feed_id{

    NSManagedObjectContext * context;

    if(![[NSThread currentThread] isMainThread]){

        context = [[NSManagedObjectContext alloc] init];

        [context setPersistentStoreCoordinator:[APP_DELEGATE persistentStoreCoordinator]];

    } else {

        context = [APP_DELEGATE managedObjectContext];

    }

    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"ENTITYNAME" inManagedObjectContext:context];

    [request setEntity:entity];

   NSPredicate * check = [NSPredicate predicateWithFormat:@"attribute == %@", Dict[@"key"]];

    [request setPredicate:check];

    NSError * error = nil;

    if ([context countForFetchRequest:request error:&error] > 0) {

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

        ENTITYNAME * fetchData = [array firstObject];

        NSString * string = fetchData.attribte[@"key"];

        return string;
    }

    return nil;
}


+(BOOL)delete{

    NSManagedObjectContext * context;

    if (![[NSThread currentThread] isMainThread]) {

        context = [[NSManagedObjectContext alloc] init];

        [context setPersistentStoreCoordinator:[APP_DELEGATE persistentStoreCoordinator]];

    } else {

        context = [APP_DELEGATE managedObjectContext];

    }

    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"ENTITYNAME" inManagedObjectContext:context];

    [request setEntity:entity];

    NSError *error = nil;

    NSBatchDeleteRequest *deleteRequest = [[NSBatchDeleteRequest alloc] initWithFetchRequest: request];

    @try{

        [context executeRequest:deleteRequest error:&error];
        if([context save:&error]){

            NSLog(@"Deleted");

            return [context save:&error];

        }
        else{

            return [context save:&error];
        }

    }
    @catch(NSException *exception){

        NSLog(@"failed %@",exception);
        return [context save:&error];
    }    


}