【问题标题】:How can I include Core Data to an already created iOS project in Xcode?如何在 Xcode 中将 Core Data 包含到已创建的 iOS 项目中?
【发布时间】:2012-04-30 22:33:08
【问题描述】:

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

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

【问题讨论】:

    标签: iphone objective-c xcode core-data


    【解决方案1】:

    Xcode 4.3.2 添加核心数据框架。

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

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

    点击“+”按钮后,您将看到下面的图像屏幕。

    要向其中添加新文件,请转到文件-> 新文件-> iOS 选项卡-> CoreData 设置。您可以选择文件

    【讨论】:

    • 您也可以将编辑器样式更改为图形视图,然后只需按(+ 添加实体)符号即可添加实体。同样为了为这个特定实体生成一个适当的 NSManagedObject 子类,选择该实体,然后在 XCode 中选择“编辑器”选项 -> 创建 NSManagedObject 子类...,它将为该实体创建对应的 .h 和 .m 文件。
    【解决方案2】:

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

    .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

    //
    //  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
    

    【讨论】:

    • 最棒的!我是 ios 新手,我一天中的大部分时间都在尝试在应用程序委托中一遍又一遍地实现数据故障,获取上下文,将其传递给视图控制器,呃!这很甜蜜,而且效果很好!
    • 比将代码放在应用程序委托中要好得多!
    【解决方案3】:

    hp iOS CoderEugene 的答案都是正确的!

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

    1. 链接并包含核心数据框架(并在项目的.pch 文件中作为导入语句这样做)
    2. 应用委托标头 (.h) 包含声明 contextmodelcoordinator(如上)的属性
    3. app delegate 的 .m 定义了 saveContextmanagedObjectContextmanagedObjectModelpersistentStoreCoordinatorapplicationDocumentDirectory 函数/方法
    4. 数据模型,如上

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2017-06-03
      • 1970-01-01
      • 2010-11-04
      相关资源
      最近更新 更多