CoreData

新建项目,
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:
这里写图片描述
这里写图片描述

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值