#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Employee.h"
@interface ViewController (){
NSManagedObjectContext *_context;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupContext];
}
-(void)setupContext{
_context = [[NSManagedObjectContext alloc] init];
// 模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存储调度器
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",doc);
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
//数据存储的类型 数据库存储路径
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
_context.persistentStoreCoordinator = store;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like 'z*n'"];
request.predicate = pre;
NSArray *emps = [_context executeFetchRequest:request error:nil];
NSLog(@"%@",emps);
}
-(void)createEmployee{
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
employee.name = @"zhangsan";
employee.age = @18;
employee.height = @1.89;
[_context save:nil];
}
转载于:https://my.oschina.net/SoulJa/blog/469173