当您编写一个使用 CoreData 的静态库时,项目中包含一个普通的 .xdatamodeld 文件,因为您不能只是将其编译版本(.momd)链接到您的二进制文件中,因此最好NSManagedObjectModel
在代码中创建整个文件,例如这:
NSAttributeDescription *dateAttribute = NSAttributeDescription.new;
dateAttribute.name = @"timestamp";
dateAttribute.attributeType = NSDoubleAttributeType;
dateAttribute.optional = NO;
dateAttribute.indexed = YES;
NSAttributeDescription *payloadAttribute = NSAttributeDescription.new;
payloadAttribute.name = @"payload";
payloadAttribute.attributeType = NSBinaryDataAttributeType;
payloadAttribute.optional = NO;
payloadAttribute.indexed = NO;
NSEntityDescription *entry = NSEntityDescription.new;
entry.name = entry.managedObjectClassName = NSStringFromClass(MyCustomEntry.class);
entry.properties = @[dateAttribute, payloadAttribute];
NSManagedObjectModel *mom = NSManagedObjectModel.new;
mom.entities = @[entry];
一切都很完美......
但!等等,如果我的实体中有多个实体NSManagedObjectModel
并且它们是相关的(对多、反向等),我将如何在代码中连接它们,就像上面的例子一样,没有那个漂亮的 Xcode 编辑器,你在哪里通过几次鼠标点击建立关系?
例子
想象一下,我们有一个 MyCustomElement 类,它与上面代码中的 MyCustomEntry 几乎相同。现在,如果我为实体使用 Xcode 生成,它们的界面如下所示:
@interface MyCustomEntry : NSManagedObject
@property (nonatomic, retain) NSNumber *timestamp;
@property (nonatomic, retain) NSData *payload;
@property (nonatomic, retain) MyCustomElement *element;
@end
@interface MyCustomElement : NSManagedObject
@property (nonatomic, retain) NSNumber * timestamp;
@property (nonatomic, retain) NSString * identifier;
@property (nonatomic, retain) NSSet *entries;
@end
@interface MyCustomElement (CoreDataGeneratedAccessors)
- (void)addEntriesObject:(MyCustomEntry *)value;
- (void)removeEntriesObject:(MyCustomEntry *)value;
- (void)addEntries:(NSSet *)values;
- (void)removeEntries:(NSSet *)values;
@end
我需要为他们创建什么 NSRelationshipDescription 以及如何初始化它?