干掉项目中的 CoreData.xcdatamodel

2016-11-08  本文已影响128人  SunnyEver0

1. CoreData.xcdatamodel

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

上一篇 下一篇

猜你喜欢

热点阅读