用CoreData存储数据(一)基础

CoreData优点:能够合理管理内存,避免使用sql的麻烦,高效

Managed Object Context (管理数据内容)

操作实际内容(操作持久层)

作用:插入数据,查询数据,删除数据 , 管理对象,上下文,持久性存储模型对象

Managed Object Model (管理数据模型)

数据库所有表格或数据结构,包含各实体的定义信息

作用:添加实体的属性,建立属性之间的关系

Persistent Store Coordinator(持久性数据协调器)

相当于数据库的连接器

作用:设置数据存储的名字,位置,存储方式,和存储时机

Managed Object

相对于数据库中的表格记录

NSFetchRequrest (获取数据的请求)

相当于查询语句

NSEntityDescription(实体结构)

相当于表格结构

后缀为.xcdatamodeld的包

里面是.xcdatamodeld文件,用数据模型编辑器编辑编译后为.momd或.mom文件

创建工程步骤:

1.创建新项目时,选择coredata

如果是已有项目,需要添加coredata库引用,并在appdelegate添加代码

代码(在Appdelegate.h中):

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

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

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

@end

.m文件里面的实现

//
//  AppDelegate.m
//  TestCoredata
//
//  Created by jerehedu on 15/2/6.
//  Copyright (c) 2015年 jereh. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

// Returns the URL to the application's Documents directory.获取Documents路径
-(NSURL *)applicationDocumentsDirectory{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
// 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:@"TestCoredata" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}
// 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) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    return _managedObjectContext;
}
// 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;
    }
     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"TestCoredata.sqlite"];
    //<span style="font-size:14px;">此句执行<span style="font-family: Arial; line-height: 26px;">以后,你可以在Documents下面看到三个文件:</span><span style="font-family: Arial; line-height: 26px;">TestCoredata.sqlite</span>,<span style="font-family: Arial, Helvetica, sans-serif;">TestCoredata.sqlite-shm</span>,<span style="font-family: Arial, Helvetica, sans-serif;">TestCoredata.sqlite-wal</span>
</span>
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return _persistentStoreCoordinator;
}

#pragma mark - Core Data Saving support
-(void)saveContext{
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = 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();
        }
    }
}

@end

2.创建实体

3.添加属性

4.添加类

5.操作数据

(未完待续)

时间: 2024-08-29 19:02:03

用CoreData存储数据(一)基础的相关文章

IOS之分析网易新闻存储数据(CoreData的使用,增删改查)

用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的. 首先: 1.网易新闻用CoreData存储了新闻列表,因为我打开网易新闻的Documents时看到了三个文件: newsapp.sqlite,newsapp.sqlite-shm,newsapp.sqlite-wal:这三个文件是你在用CoreData时自动生成的.所以我确定他是用coredata存储的数据而不是sqlite数据库.(Core

CoreData 持久化数据存储的注意点

CoreData 是iOS3.0之后实现数据持久化存储的一种重要手段.下面是整理的一些注意点: 要使用CoreData对数据进行操作,首先需要写数据管理器的取值函数(来自AppDelegate) CoreData的实体创建不能用alloc,而需要用NSEntityDescription CoreData每次操作之后需要同步,也就是save 增 NSEntityDescription: 的方法: + (id)insertNewObjectForEntityForName:(NSString *)e

[安卓基础]011存储数据(中)——sqlite语法介绍

*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } a { color: #4183C4; text-decoration: none; } a.absent { color: #cc0000; } a.anchor { display: block; padding-left: 30px; margin-left: -30px; cursor: poin

CoreData 本地数据存储

在iOS开发中,我们会用到本地数据文件的存储,一般有属性列表Plist,SQLite,CoreDate以及沙盒文件等方式,现在归纳一下CoreData. CoreData是苹果iOS 5后提供的本地文件存储框架,利用CoreData可以方便创建关系映射,进行数据CRUD(增删改查)操作. <注意>使用CoreData处理数据务必先引入CoreData框架包:CoreData.framework: 1.创建CoreData文件的两种方式 (a).在使用CoreData时我们需要进行CoreDat

[安卓基础]010. 存储数据(上)

*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } a { color: #4183C4; text-decoration: none; } a.absent { color: #cc0000; } a.anchor { display: block; padding-left: 30px; margin-left: -30px; cursor: poin

[安卓基础] 012.存储数据(下)——文件存储

*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } a { color: #4183C4; text-decoration: none; } a.absent { color: #cc0000; } a.anchor { display: block; padding-left: 30px; margin-left: -30px; cursor: poin

iOS 通过CoreData实现数据持久化

iOS 通过CoreData实现数据持久化引言: Core Data 是 iOS 3.0 以后引入的数据持久化解决方案,其原理是对 SQLite 的封装,是开发者不需要接触 SQL 语句,就可以对数据库进行的操作. 其编码方式和原理结构方面较为特殊,本博文主要介绍在使用 Core Data 时遇到的各种问题以及对其核心原理进行解释. 参考资料: 1: iOS 教程:Core Data 数据持久性存储基础教程 http://www.dasheyin.com/ios_jiao_cheng_core_

2017最新大数据零基础视频教程下载

2017零基础大数据就业课程(全网最全,856课时) 课程观看地址:http://www.xuetuwuyou.com/course/181 课程出自学途无忧网:http://www.xuetuwuyou.com 本套课程是风舞烟老师团队历时四个月打造的全网最全的一套大数据就业课程.可以说是完全0编程基础起步,一部到就业!课程分2大模块,14个课程,65章,共计856课时! 课程大纲: 一.Java模块课程 课程一.[大数据必知必会]- Java负基础扫盲篇 01.Java基础语法.变量.数据类

《Entity Framework 6 Recipes》翻译系列 (3) -----第二章 实体数据建模基础之创建一个简单的模型 (转)

第二章 实体数据建模基础 很有可能,你才开始探索实体框架,你可能会问“我们怎么开始?”,如果你真是这样的话,那么本章就是一个很好的开始.如果不是,你已经建模,并在实体分裂和继承方面感觉良好,那么你可以跳过本章. 本章将带你漫游使用实体框架建模的基本实例,建模是实体框架的核心特性,同时也是区别实体框架和微软早期的数据访问平台的特性.一旦建好模,你就可以面向模型编写代码,而不用面向关系数据库中的行和列. 本章以创建一个简单概念模型的实例开始,然后让实体框架创建底层的数据库,剩下的实例,将向你展示,如