core data in a static library for the iPhone

后端 未结 8 1213
不知归路
不知归路 2020-11-28 02:07

I\'ve built a static library that makes heavy use of the Core Data framework. I can successfully use the library in my external project, but ONLY if I include the .xcdatamod

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 02:31

    Note that instead of using xcdatamodel/mom file you can also create your model in code (especially if you have a simple model) and this way you won't need to create an additional bundle for resources. Here is a simple example with one table that contains two attributes:

    - (NSManagedObjectModel *)coreDataModel
    {
        NSManagedObjectModel *model = [NSManagedObjectModel new];
    
        NSEntityDescription *eventEntity = [NSEntityDescription new];
        eventEntity.name = @"EventEntity";
        eventEntity.managedObjectClassName = @"EventEntity";
    
        NSAttributeDescription *dateAttribute = [NSAttributeDescription new];
        dateAttribute.name = @"date";
        dateAttribute.attributeType = NSDateAttributeType;
        dateAttribute.optional = NO;
    
        NSAttributeDescription *typeAttribute = [NSAttributeDescription new];
        typeAttribute.name = @"type";
        typeAttribute.attributeType = NSStringAttributeType;
        typeAttribute.optional = NO;
    
        eventEntity.properties = @[dateAttribute, typeAttribute];
        model.entities = @[eventEntity];
    
        return model;
    }
    

    Here is a tutorial about creating model from code: https://www.cocoanetics.com/2012/04/creating-a-coredata-model-in-code/

    Also based on this approach I created a small and easy to use library that might fit your needs called LSMiniDB so you can check it also.

    Also in my case I had warnings such as "warning: dynamic accessors failed to find @property implementation..." on the console while using properties of NSManagedObject subclasses. I was able to fix that by moving those properties to a class interface/implementation instead of having them in a category in a separate file (currently xcode by default is generating this code splited into separate files ClassName+CoreDataClass and ClassName+CoreDataProperties with a class and a category for each subclass).

提交回复
热议问题