CoreData

原创 2015年11月20日 20:07:43

新建项目,
soga
如果忘了勾选use Core Data, 想在中途使用Core Data, 则可以自己写一个单例, 代码如下(这些, 可以新建一个工程, 从AppDelegate中复制粘贴):
CoreDataManager.h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataManager : NSObject

+ (CoreDataManager *)defaults;

//  数据管理器类
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
//  模型管理器类
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
//  连接器
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

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

@end

CoreDataManager.m

#import "CoreDataManager.h"

@implementation CoreDataManager

+ (CoreDataManager *)defaults {
    static CoreDataManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CoreDataManager alloc] init];
    });

    return manager;
}

#pragma mark - Core Data stack

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

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "ligen.CoreData_52" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData_52" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    // Create the coordinator and store

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData_52.sqlite"];
    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]) {
        // Report any error we got.
        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];
        // Replace this 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();
    }

    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#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

在storyboard中拖四个按钮:
soga
在ViewController.m:

#import "ViewController.h"
#import "CoreDataManager.h"
#import "Student.h"

@interface ViewController ()
@property(nonatomic, strong)CoreDataManager *manager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];

    self.manager = [CoreDataManager defaults];

    NSLog(@"url =====   %@", [self.manager applicationDocumentsDirectory]);


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)add:(UIButton *)sender {
    //  创建实体描述
    //  参数1: 描述的实体
    //  参数2: 数据管理器
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[self.manager managedObjectContext]];

    //  创建实体
    //  参数1: 实体描述
    //  参数2: 数据管理器
    Student *stu = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
    stu.name = @"成精";
    stu.age = @1000;
    stu.sex = @"?";
    stu.hobby = @"fdsa";
    stu.number = @10;

    [self.manager saveContext];
}

//  查找
- (IBAction)select:(UIButton *)sender {

    //  获取查询数据的请求, 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];

    //  添加约束    谓词
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], @"成精"];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], @"成精"];

    request.predicate = predicate;

    //  通过某个key给数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];


     NSError *error;

    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];

    NSLog(@"%ld", array.count);


}

//  修改
- (IBAction)update:(UIButton *)sender {

    //  获取查询数据的请求, 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];

    //  添加约束    谓词
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], @"成精"];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], @"成精"];

    request.predicate = predicate;

    //  通过某个key给数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];


    NSError *error;

    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];

    Student *stu = [array lastObject];
    stu.sex = @"女";

    [self.manager saveContext];

}

//  删除
- (IBAction)delete:(UIButton *)sender {

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"sex", @"%@"], @"?"];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sex" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

    NSError *error = nil;
    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (Student *stu in array) {

        [self.manager.managedObjectContext deleteObject:stu];
    }

    [self.manager saveContext];


}
@end

如果建立工程时勾选了Core Data, 会自带一个 .xcDataxcdatamodelld, 里面添加实体的属性, 若想在后来添加新的属性, 想要新建一个 .xcDataxcdatamodelld, command + N,soga
原本建立的.xcDataxcdatamodelld
这里写图片描述
在添加两条属性:
这里写图片描述
增加新属性后需要一个Mapping Model:
这里写图片描述
这里写图片描述

添加实体属性后, 需要建立
这里写图片描述
会自动根据实体属性生成四个文件:
这里写图片描述
增加属性后, 还需要添加:
如图

版权声明:本文为博主原创文章,未经博主允许不得转载。

coreData增删改查Demo

  • 2015年06月10日 15:31
  • 121KB
  • 下载

iphone中 CoreData 框架的简单解释

并非严格的说, CoreData是对sqlite数据库的一个封装. sqlite数据库操作的基本流程是, 创建数据库, 再通过定义一些字段来定义表格结构, 可以利用sql语句向表格中插入记录, ...
  • dylgsy
  • dylgsy
  • 2013年05月09日 18:50
  • 765

CoreData ChildContext

  • 2015年06月01日 13:52
  • 568KB
  • 下载

简单的数据库操作coredata

  • 2015年07月20日 09:21
  • 70KB
  • 下载

iOS 使用CoreData处理大量数据

在CoreData中想要更新大量数据,我们往往要将大量修改后的 NSManagedObject 加载到 NSManagedObjectContext 中并保存,这会占用大量内存,如果超过了系统限制,那...

coredata存储

  • 2014年11月16日 22:41
  • 150KB
  • 下载

CoreData数据存储demo

  • 2014年08月07日 15:42
  • 76KB
  • 下载

iOS CoreData数据迁移

Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 13410...

CoreData学习入门

  • 2016年08月17日 11:36
  • 42KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:CoreData
举报原因:
原因补充:

(最多只允许输入30个字)