1. CoreData.xcdatamodel
- 这个文件是在使用coredata轻量数据库时,Xcode自动生成的文件,经查看相应数据发现,这个文件的用途及在于创建NSManagedObjectModel这个对象(即我们需要使用的数据模型),在Xcode中自己加载这个数据模型,是在appdelegate.m生成并采用的下面这段代码:
- (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" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
从这段代码里面我们可以看到这个CoreData.xcdatamodel文件只是用于生成相应的
NSManagedObjectModel,所以我们可不可以用代码尝试实现呢?
- (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" withExtension:@"momd"];
// _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
/**< 手动初始化方式 */
_managedObjectModel = [[NSManagedObjectModel alloc] init];
/**< 初始化实例数组 */
NSMutableArray *entities = [NSMutableArray array];
/**< 初始化单个实例对象 */
NSEntityDescription *description = [[NSEntityDescription alloc] init];;
[description setName:@"Teacher"];
[description setManagedObjectClassName:@"Teacher"];
NSArray *attributesArray = [NSArray array];
NSAttributeDescription *name = [[NSAttributeDescription alloc] init];
[name setName:@"name"];
[name setAttributeType:NSStringAttributeType];
NSAttributeDescription *age = [[NSAttributeDescription alloc] init];
[age setName:@"age"];
[age setAttributeType:NSStringAttributeType];
NSAttributeDescription *address = [[NSAttributeDescription alloc] init];
[address setName:@"address"];
[address setAttributeType:NSStringAttributeType];
NSAttributeDescription *phone = [[NSAttributeDescription alloc] init];
[phone setName:@"phone"];
[phone setAttributeType:NSStringAttributeType];
attributesArray = @[name,age,address,phone];
description.properties = attributesArray;
[entities addObject:description];
_managedObjectModel.entities = entities;
NSLog(@"%@",_managedObjectModel.description);
return _managedObjectModel;
}
这样初始化NSManagedObjectModel之后我们就可以不用项目中的xcdatamodel文件了。项目的集成度更加的高了。