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

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

我已经创建了一个几乎完成的实用程序应用程序,但现在我真的必须保留数据。

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

或者我应该从一个新的基于窗口的应用程序开始,包括。核心数据并尝试手动构建实用程序/反面部分?

有人可以建议我适合我情况的最佳做法吗?

最佳答案

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

第 1 步:添加 CoreData.framework

a) 在“链接的框架和库”下的“项目目标摘要”中,使用 + 按钮添加 CoreData.framework
b) 选择"file"/“新建”/"file",然后在“核心数据”部分添加一个新的“数据模型”(并将其命名为 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 ma​​nagedObjectModelpersistentStoreCoordinator 中,您必须将 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];
}

关于iphone - 如何将核心数据添加到现有实用程序应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1528341/

相关文章:

ios - 当应用程序处于后台时开始播放 MPMusicPlayerController

ios - 模仿 tableView :willBeginEditingRowAtIndexPath: on UIViewController 的 UITableViewControllers 行为

iphone - 有哪些技巧可以让您的 iPad 应用程序快如闪电?

iphone - 如何在应用商店中知道应用程序是通用的还是有 2 个二进制文件

iphone - 将应用程序功能分配给 iOS 中的静音/静音开关

iphone - cocoa - 将 double 转换为字符串

iphone - 如何一一禁用 UITableViewCell 选择?

iphone - 如何在 iOS 中拍照并将其作为电子邮件附件发送

iphone - 在 MKMapView 上搜索并显示营业地点

iphone - iPhone SDK 4 内置应用程序中的 Google Analytics