CoreData

来源:互联网 发布:淘宝女装店铺推荐 编辑:程序博客网 时间:2024/06/01 09:45

//

//  ViewController.m

//  XMCoreData

//

//  Created by Floating_SH on 15/12/28.

//  Copyright © 2015 SH. All rights reserved.

//


#import "ViewController.h"

// 第一步引入头文件

#import <CoreData/CoreData.h>

#import "Employee.h"


@interface ViewController ()


@property (nonatomic,strong)NSManagedObjectContext *context;


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    

    // 配置协调器,它连接三部分

    // 协调器->数据模型

    // 协调器->数据库

    // 协调器->上下文

    

    

    // 协调器->模型

    NSManagedObjectModel *model = [NSManagedObjectModelmergedModelFromBundles:nil];

    NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:model];

    

    // 协调器->上下文

    // 创建一个上下文对象

    self.context = [[NSManagedObjectContextalloc]initWithConcurrencyType:NSMainQueueConcurrencyType];

    // 该上下文对象的协调器指向我们刚才创建的协调器

    self.context.persistentStoreCoordinator = persistentStoreCoordinator;

    

    // 协调器与数据库

    NSString *DocumentPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];

    NSString *dataBasePath = [DocumentPath stringByAppendingFormat:@"XMCoreData.sqlite"];

    

    [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:[NSURLfileURLWithPath:dataBasePath] options:nilerror:nil];

    

    NSLog(@"%@",dataBasePath);

    

    

}


// 增加一个新员工

- (IBAction)insertAction:(id)sender {

    

    Employee *emp = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Employee"inManagedObjectContext:self.context];

    emp.name = @"张三";

    emp.height = @170;

    emp.birthday = [NSDatedate];

    

    

    [self.contextsave:nil];

    

}


//

- (IBAction)selectAction:(id)sender {

    

    

    

    // 先填写一份查询表

    NSFetchRequest *request = [NSFetchRequestfetchRequestWithEntityName:@"Employee"];

    

    // 填写查询条件

    NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"1=1"];

    request.predicate = predicate;

    

    // 排序条件

    request.sortDescriptors =@[[NSSortDescriptorsortDescriptorWithKey:@"birthday"ascending:YES]];

    

    // 执行请求返回结果.

    NSArray *array = [self.contextexecuteFetchRequest:request error:nil];

    

    for (Employee *empin array) {

        NSLog(@"name = %@,height = %@,birthday = %@",emp.name,emp.height,emp.birthday);

    }

}


//

- (IBAction)updateAction:(id)sender {

    

    // 查询.(fetch)

    NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];

    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Employee"inManagedObjectContext:self.context];

    [fetchRequest setEntity:entity];

    // Specify criteria for filtering which objects to fetch

    NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"1=1"];

    [fetchRequest setPredicate:predicate];

    // Specify how the fetched objects should be sorted

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptoralloc] initWithKey:@"birthday"

                                                                   ascending:YES];

    [fetchRequest setSortDescriptors:[NSArrayarrayWithObjects:sortDescriptor, nil]];

    

    NSError *error = nil;

    NSArray *fetchedObjects = [self.contextexecuteFetchRequest:fetchRequest error:&error];

    if (fetchedObjects == nil) {

        //

        NSLog(@"");

    }

    

    // 修改fetchedObjects即可

    for (Employee *empin fetchedObjects) {

        emp.name = @"李四";

    }

    

    // 保存上下文

    [self.contextsave:nil];

}


//

- (IBAction)deleteAction:(id)sender {

    

    NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];

    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Employee"inManagedObjectContext:self.context];

    [fetchRequest setEntity:entity];

    // Specify criteria for filtering which objects to fetch

    NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"1=1"];

    [fetchRequest setPredicate:predicate];

    // Specify how the fetched objects should be sorted

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptoralloc] initWithKey:@"birthday"

                                                                   ascending:YES];

    [fetchRequest setSortDescriptors:[NSArrayarrayWithObjects:sortDescriptor, nil]];

    

    NSError *error = nil;

    NSArray *fetchedObjects = [self.contextexecuteFetchRequest:fetchRequest error:&error];

    if (fetchedObjects == nil) {

        //

    }

    

    // 开始删除

    for (Employee *empin fetchedObjects) {

        [self.contextdeleteObject:emp];

    }

    

    [self.contextsave:nil];

}




- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end





//

//  Employee+CoreDataProperties.h

//  XMCoreData

//

//  Created by Floating_SH on 15/12/28.

//  Copyright © 2015 SH. All rights reserved.

//

//  Choose "Create NSManagedObject Subclass…" from the Core Data editor menu

//  to delete and recreate this implementation file for your updated model.

//


#import "Employee.h"


NS_ASSUME_NONNULL_BEGIN


@interface Employee (CoreDataProperties)


@property (nullable,nonatomic, retain)NSString *name;

@property (nullable,nonatomic, retain)NSNumber *height;

@property (nullable,nonatomic, retain)NSDate *birthday;


@end


NS_ASSUME_NONNULL_END





//

//  Employee+CoreDataProperties.m

//  XMCoreData

//

//  Created by Floating_SH on 15/12/28.

//  Copyright © 2015 SH. All rights reserved.

//

//  Choose "Create NSManagedObject Subclass…" from the Core Data editor menu

//  to delete and recreate this implementation file for your updated model.

//


#import "Employee+CoreDataProperties.h"


@implementation Employee (CoreDataProperties)


@dynamic name;

@dynamic height;

@dynamic birthday;


@end











0 0
原创粉丝点击