如何将核心数据添加到现有的实用程序

时间:2009-10-06 22:02:22

标签: iphone cocoa-touch iphone-sdk-3.0 core-data

我已经创建了一个几乎完成的实用程序应用程序,但是现在我确实需要坚持Data。

由于XCode仅在导航或基于窗口的应用程序中提供核心数据模板,是否有一种简单的方法可以将核心数据添加到我的应用程序中?我从未使用过Core Data,只需要保存460个字符和联系人名称的消息,将其作为发送消息的历史记录。

或者我应该从一个新的基于Window的应用程序开始。 Core Data并尝试手工构建Utility / Flipside Part?

有人可以根据我的情况向我推荐最佳做法吗?

3 个答案:

答案 0 :(得分:18)

由于我也试图理解核心数据的twighlightzone,我想出了以下步骤将“正常”项目迁移到核心数据(通过将空应用程序项目与核心数据的空应用程序项目进行比较)

第1步:添加CoreData.framework

a)在“链接的框架和库”下的“项目目标摘要”中,使用+按钮添加CoreData.framework b)选择文件/新建/文件,然后在“核心数据”部分添加一个新的“数据模型”(并称之为XXXXXXX(命名参见3.b)
c)在APPLIKATION-Prefix.pch文件中(其中APPLICATION是您的项目名称)添加

   #import <CoreData/CoreData.h>

另外两个包含指令

第2步:在AppDelegate.h中添加以下属性/方法声明:

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

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

第3步: AppDelegate.m

a)同步属性:

@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
在模块末尾的

b)添加以下行:

重要:在了Methode managedObjectModel persistentStoreCoordinator 您必须更换XXXXXXX枝条个人.xcdatamodeld文件的名称

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *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. 
             */
            NSLog(@"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.
 */
- (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 from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"XXXXXXX" withExtension:@"momd"];
    __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 (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"XXXXXXX.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. 

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

答案 1 :(得分:9)

您需要将CoreData框架添加到目标,创建数据模型,并实例化NSManagedObjectModelNSPersistentStoreCoordinatorNSManagedObjectContext对象。

this Apple document(搜索“现有应用程序”)中简要讨论了向现有应用程序添加核心数据

您还应该查看Apple tutorial以了解所涉及的内容。

您也可以考虑使用SQLite。

答案 2 :(得分:6)

使用提供的模板在XCode中创建一个新项目 - 找一个有一个框来检查是否使用Core Data进行存储。

它为您提供了一个xcdatamodel文件,以及应用程序委托中的一些代码/类变量,您可以将这些变量从该项目复制到当前项目中。

我也强烈推荐nall提到的Apple教程。

如果您决定直接使用SQLLite,请强烈考虑使用FMDB,这样可以简化SQL代码。这是您添加到项目中的一个文件。