iOS 在已有项目添加CoreData
本文转载至 http://cnbin.github.io/blog/2016/03/11/ios-zai-yi-you-xiang-mu-tian-jia-coredata/
如果是新项目很好说,新建的时候选上use coredata就行。 要是我们在遗留项目里面想添加CoreData怎么办呢?也有办法,期间找了很多文章,发现全部都说copy的,而且中间貌似害你掉了很多东西。没办法,于是想着新建一个demo项目,把coredata的支持搬过来,发现真可行,下面就来说说过程吧!
1.添加CoreData框架
单击项目,选择Build Phases,继续选择Link Binary With Libraries,点假+号,搜索CoreData,Add就可以了。
2.修改perFix.pch文件
注意第11行
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "NSObject+Subscripts.h"
#import <CoreData/CoreData.h>
#endif
3.新建xcdatamodeld文件
添加文件。New File选择Core Data -》 Data Model 文件名称就是你的项目名!
4.修改AppDelegate.h文件
增加以下代码
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory;
- (void)saveContext;
5.修改AppDelegate.m文件
增加以下代码
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
#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:@"mima96_iphone" 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:@"mima96_iphone.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:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
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];
}
#pragma mark function
- (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();
}
}
}
这样你就可以在项目里面使用CoreData了!稍后还会放出具体怎么使用CoreData的例子,等我先研究研究吧!
iOS 在已有项目添加CoreData的更多相关文章
- visual studio 2015将已有项目添加到码云(gitee)
visual studio 2015将已有项目添加到码云的步骤包括:gitee新建项目.清空项目及VS发布项目 1.gitee新建项目 2.清空项目 清空项目则会将vs项目的master分支发布到gi ...
- idea git操作 -- 已有项目添加到git
我们在使用git时,如果是先从git克隆项目,然后配置项目运行没问题,如果将已有项目添加到git,则项目环境还是提交不了git,还需要到克隆的仓库文件夹打开项目去操作git,如果有有类型情况可按照如下 ...
- IOS之UI--小实例项目--添加商品和商品名(纯代码终结版)
前言:这个小实例项目是完完全全以MJ视频传授的优化方案一步一个思路从零开始敲出代码的,而且每一步都有思路,都有逻辑所以然.敲代码讲究思路,我个人不建议记忆太多东西,反正我记性很差的. 小贴士:文章末尾 ...
- 在vscode 中使用Git -- 已有项目添加到git
本文使用与在已经存在本地项目的情况下将本地项目添加到git中管理,本地不存在项目则可以直接从Git上克隆下来后再创建项目目录更方便. 创建远程Git 仓库 如果Git 仓库已存在,可直接参考下一部,不 ...
- iOS 如何给Xcode7项目添加“.pch”文件
1.首先打开你的项目(演示使用一个空的项目),按照以下步骤即可 找到“Supporting Files”文件夹,右键即可看到下图,选择“New File...” 2.选择"iOS" ...
- GitHub练习——如何将本地已有项目添加到github
刚开始开始接触,搞点简单的,看看是怎么把项目传上去,总结一下,大概是这些步骤: 创建本地仓库 将本地仓库变成git可管理的仓库:git init 把项目文件添加到缓存区:项目文件添加到已有的仓库,然后 ...
- IOS之UI--小实例项目--添加商品和商品名(使用xib文件终结版) + xib相关知识点总结
添加商品和商品名小项目(使用xib文件终结版) 小贴士:博文末尾有项目源码在百度云备份的下载链接. xib相关知识点总结 01-基本使用 一开始使用xib的时候,如果要使用自定义view的代码,就需要 ...
- IOS之UI--小实例项目--添加商品和商品名
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- iOS开发-为我们的项目添加头文件prefix header
在XCode6新建项目时,不再自动创建头文件,因此我们需要手动添加. 点击我们的项目->Build Settings -> all -> 搜索“prefix” -> 修改pre ...
随机推荐
- 概念:CountDownLatch、CyclicBarrier、Semaphore,以及guava的RateLimiter
概念 CountDownLatch:一个门闩,作用是将某个线程关在门外,等门里的人分赃完毕(计数为0)的时候,才会打开门,让外面的那个线程执行. CyclicBarrier:直译的话,就是循环障碍.貌 ...
- Java如何创建用户自定义异常?
在Java编程中,如何创建用户自定义异常? 此示例显示如何通过扩展Exception类来创建用户定义的异常. package com.yiibai; class MyException extends ...
- VMWare中Linux虚拟机设置静态IP上网的设置方法
VMWare中Linux虚拟机设置静态IP上网的设置方法 标签: vmwareLinux虚拟机securecrt静态IP上网 2016-05-18 02:30 702人阅读 评论(0) 收藏 举报 ...
- XAudio2学习之调节音调
频率比有两个地方能够设置.一个是在创建IXAudio2SourceVoice对象的时候.一个是调用IXAudio2SourceVoice::SetFrequencyRatio来调节. 在创建IXAud ...
- C# 根据第几周和季度 获取开始时间和结束时间
/// <summary> /// 根据第几周 获取开始时间和结束时间 /// </summary> /// <param name="week"&g ...
- linux中find命令
1.使用name选项: 文件名选项是find命令最常用的选项,要么单独使用该选项,要么和其他选项一起使用. 可以使用某种文件名模式来匹配文件,记住要用引号将文件名模式引起来. 不管当前路径是什么,如果 ...
- tf.variable_scope
转载:https://blog.csdn.net/gaoyueace/article/details/79079068 例如: #在名字为ae的命名空间内创建变量 with tf.variable_s ...
- iPhone 配置使用工具
“iPhone 配置实用工具”可让您轻松地创建.维护和安装配置描述文件及对配置描述文件进行加密,跟踪和安装预置描述文件与授权的应用程序,以及采集包括控制台日志在内的设备信息. http://suppo ...
- 百度编辑器插入视频、iframe 失败
插入失败是因为编辑器的xssFilter过滤,导致插入出现异常 文件位置:ueditor.config.js ,大概在428行加上 video: ['autoplay', 'controls', 'l ...
- MyEclipse如何恢复删掉的文件
今天一不小心删了项目里的两个包,心里那个痛啊,一想MyEclipse这么强大,应该会有恢复文件的功能吧,要不就太坑了啊. 果不其然让我找到了方法: 如图:右击项目选择 然后在弹出的页面勾选需要恢复的文 ...