干掉项目中的 CoreData.xcdatamodel

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文件了。项目的集成度更加的高了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容