用CoreData存储数据(一)基础

来源:互联网 发布:wamp 连接sqlserver 编辑:程序博客网 时间:2024/05/16 17:54

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.操作数据

(未完待续)


0 0