`

添加 core data 支持 ios 项目

    博客分类:
  • ios
阅读更多

网上很多教程包括apple自己的都是从一个core data的模板项目教起, 没有一个怎么在既有的项目上添加core data的方法(也许有,反正我没找到), 下面就是自己研究的添加core data的步骤, 我用的是mac os x 10.6.7, xcode4.0.0

 

 

1.  添加core data framework 

xcode中选中项目根,在右边的面板中选中targets下面的项目名,再在右边选中 Build Phases, 再选中Link Binary with Libraries,  点加号添加core data 框架

 

   在项目中找一个xx.pch的文件, 加上一行      #import <CoreData/CoreData.h>

 

2. 在项目的XXXAppDelegate.h 文件中 加入

 

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


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

XXXAppDelegate.m文件中加入

 

 

@synthesize managedObjectContext=__managedObjectContext;//session

@synthesize managedObjectModel=__managedObjectModel;

@synthesize persistentStoreCoordinator=__persistentStoreCoordinator;



//相当与持久化方法
- (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. 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]);
            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.
 */
//初始化context对象
- (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;
    }
//这里的URLForResource:@"lich" 的url名字(lich)要和你建立datamodel时候取的名字是一样的,至于怎么建datamodel很多教程讲的很清楚
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"lich" 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;
    }
    //这个地方的lich.sqlite名字没有限制,就是一个数据库文件的名字
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"lich.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.
         
         
         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];
}

 

因为加入了新的属性,自己记得去release

 

这里比较奇怪的一点是RLForResource:@"lich" withExtension:@"momd"]; 扩展名是momd 而不是xcdatamodeld,不明白

 

上面很多代码是从core data模板项目里copy过来的,大致的意思就是先建立一个managedObjectModel,

然后根据 managedObjectModel 建立 persistentStoreCoordinator

然后根据 persistentStoreCoordinator 建立 managedObjectContext

 

3. 然后是把managedObjectContext传给真正要使用数据的 viewcontroller

 

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   // NSLog(@"%@===================", [self applicationDocumentsDirectory]);
    [self.window makeKeyAndVisible];
    NSManagedObjectContext *context = [self managedObjectContext];
    NSArray *array =  self.tabBarController.viewControllers;
    for (UINavigationController *navi in array) {
        RootView *rv = (RootView *)navi.topViewController;
        rv.context = context;
    }
 

 

 

我开始不明白为什么要在XXXAppDelegate中建立managedObjectContext 而不是在viewcontroller中,那样就不用传来传去了啊

也许是view对象有时候会被销毁吧

 

 

至于其他的怎么插数据 读数据, apple教程上都有就不讲了。

 

 

 

 

 

 

 

 

 

分享到:
评论
1 楼 mr.pppoe 2011-05-30  
谢谢lz,补充一点

引用
这里比较奇怪的一点是RLForResource:@"lich" withExtension:@"momd"]; 扩展名是momd  而不是xcdatamodeld,不明白


xcdatamodeld文件是编译前的状态,这个文件在编译时会被转为momd文件被拷贝到App的main bundle里

相关推荐

    Pro Core Data for IOS

    本书《Pro Core Data for iOS》以完全更新的形式针对Xcode 4.2版本,涵盖了iOS SDK 5环境下Core Data框架的使用方法。Core Data是苹果公司推出的数据存储和检索技术,它对于开发者来说易于上手,但深入掌握却颇具...

    Core Data iOS iOS iOS

    在iOS开发中,Core Data是苹果提供的一种强大的数据管理框架,用于处理应用程序的数据模型层。它不仅简化了数据存储,还提供了对象关系映射(ORM)功能,将数据库操作转化为面向对象的编程。本篇文章将深入探讨如何...

    Pro Core Data for iOS.pdf

    ### Pro Core Data for iOS:iOS应用数据访问与持久化引擎详解 #### 一、书籍概述 《Pro Core Data for iOS》是一本专为iOS开发者编写的深入探讨Core Data框架的书籍。Core Data作为iOS和macOS开发中的一个关键...

    Pro Core Data for iOS, Second Edition

    Fully updated for Xcode 4.2, Pro Core Data for iOS explains how to use the Core Data framework for iOS SDK 5 using Xcode 4.2. The book explains both how and why to use Core Data, from simple to ...

    [iOS] Learning Core Data for iOS (英文版)

    [Addison-Wesley Professional] Learning Core Data for iOS A Hands-On Guide to Building Core Data Applications (E-Book) ☆ 图书概要:☆ This is the first Core Data book to fully reflect Apple’s ...

    Core.Data.in.Swift.Data.Storage.and.Management.for.iOS.and.OSX

    Discover the powerful capabilities integrated into Core Data, and how to use Core Data in your iOS and OS X projects. All examples are current for OS X El Capitan, iOS 9, and the latest release of ...

    Core Data iOS Essentials

    ### Core Data iOS Essentials #### 一、概述 《Core Data iOS Essentials》是一本关于iOS应用程序开发的专业书籍,主要聚焦于如何使用Core Data框架来管理数据。本书由B. M. Harwani撰写,并由Packt Publishing...

    Core Data by Tutorials v4.0 (Swift 4)

    本教程《Core Data by Tutorials v4.0》将详细解释以上概念,并通过实际项目演示如何在Swift 4环境中集成和使用Core Data。它会引导你逐步构建应用,涵盖从简单的数据存储到高级的查询和数据同步。无论你是初学者...

    Core_Data_by_Tutorials_v6.0.0.zip (iOS13 & Swift5.1 & Xcode11)

    In this book, you'll master Core Data in iOS using Swift. Comprehensive coverage of Core Data, from beginner to advanced topics. Covers setting up a Core Data Stack, data modeling, versioning and ...

    Learning Core Data for iOS(Addison,2013)

    This is the first Core Data book to fully reflect Apple's latest platform innovations, including its dramatic recent improvements to iCloud support. Hands-on from start to finish, it teaches you step-...

    Learning Core Data for iOS with Swift(2nd) 无水印pdf

    Learning Core Data for iOS with Swift(2nd) 英文无水印pdf 第2版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如...

    IOS Core data

    IOS Core data A feature comparison of different frontend frameworks3 • Todo MVC - Todo list implemented in the many different types of frontend frameworks4

    Core Data for iOS Developing Data-Driven Applications for the iPad, iPhone, epub

    Core Data for iOS Developing Data-Driven Applications for the iPad, iPhone, and iPod touch 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书

    Core Data for iOS Developing Data-Driven Applications for the iPad, iPhone, mobi

    Core Data for iOS Developing Data-Driven Applications for the iPad, iPhone, and iPod touch 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书

    Core.Data.iOS.Essentials

    Harwani撰写,是关于iOS开发中核心数据管理框架——Core Data的一部详尽指南。本书通过快速、示例驱动的方式,深入讲解了如何利用Core Data来构建数据驱动的iPhone、iPad以及iPod Touch应用程序。以下是基于该书...

    ios-Data.zip

    2. **Core Data**:Apple的Core Data框架是iOS和macOS开发中的首选数据管理工具,提供了一种模型驱动的方式去管理对象图及持久化。它负责对象的生命周期管理,包括创建、修改、删除以及与SQLite、Binary、XML等不同...

Global site tag (gtag.js) - Google Analytics