我的应用程序中有一些代码生成核心数据模型并用一组NSEntityDescription
s 填充它。然后,这些实体描述中的每一个都NSPropertyDescription
为它们分配了任意数量的 s。这些属性是NSAttributeDescription
s 和NSRelationshipDescription
s 的组合。所有关系都与现有关系匹配,并且使用 将它们设置为彼此的逆setInverseRelationship:
。
属性属性工作正常,多对关系工作正常;我已经彻底测试过了。问题似乎与值为 1NSRelationshipDescription
的 s 相关,这意味着属性描述返回的值为。当为这些类型的关系设置属性时,当我尝试保存任何使用该关系的对象时,Core Data 崩溃并出现错误:maxCount
isToMany
NO
inverseRelationship
2013-11-09 11:17:15.068 Directory[1344:5c03] -[NSManagedObject count]: unrecognized selector sent to instance 0x9643820
2013-11-09 11:17:15.074 Directory[1344:5c03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject count]: unrecognized selector sent to instance 0x9643820'
*** First throw call stack:
(
0 CoreFoundation 0x01f9f5e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x01d228b6 objc_exception_throw + 44
2 CoreFoundation 0x0203c903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x01f8f90b ___forwarding___ + 1019
4 CoreFoundation 0x01f8f4ee _CF_forwarding_prep_0 + 14
5 CoreData 0x0083c128 -[NSSQLCore _knownOrderKeyForObject:from:inverseToMany:] + 200
6 CoreData 0x00773080 -[NSSQLCore _populateRowForOp:withObject:] + 1120
7 CoreData 0x00789157 -[NSSQLCore recordValuesForInsertedObject:] + 71
8 CoreData 0x00771e8d -[NSSQLCore recordChangesInContext:] + 685
9 CoreData 0x00770c55 -[NSSQLCore saveChanges:] + 565
10 CoreData 0x0073d88c -[NSSQLCore executeRequest:withContext:error:] + 412
11 CoreData 0x0073d380 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 4704
12 CoreData 0x00769ffc -[NSManagedObjectContext save:] + 764
13 Directory 0x0002f2bf -[ETDatabaseController save] + 111
14 Directory 0x0002ba9c -[ETDataLoader performImportWithData:] + 10284
我从中收集到的暗示是,当情况并非如此时,它正在考虑逆向关系是一对多关系。根据我的断言,我对每段关系的了解是:
relationDescription.inverseRelationship != nil
[relationDescription.inverseRelationship.inverseRelationship isEqual:relationDescription]
我通过创建模型并用一小组样本数据填充它来测试这一点。目前,具有任何类型的属性、多对多关系(有/无逆向)和一对一关系(无逆向)的对象始终如一地工作。当我尝试与反向关系建立一对一关系时,问题就出现了。
这似乎有点令人费解,所以如果我需要更好地澄清什么,请告诉我。谢谢!
编辑1:
关系创建分两步完成,首先创建所有关系,然后使用查找建立每个关系的逆。
NSRelationshipDescription *description = [[NSRelationshipDescription alloc] init];
[description setName:self.name];
[description setDestinationEntity:entity];
[description setMaxCount:(isToMany ? 0 : 1)];
[description setMinCount:0];
[description setOrdered:YES]; // See you in a minute
之后...
NSEntityDescription *inverseEntity = newRelationship.destinationEntity;
NSRelationshipDescription *inverseRelationDescription = [inverseEntity relationshipsByName][inverse.name];
if (inverseRelationDescription) {
inverseRelationDescription.inverseRelationship = newRelationship;
newRelationship.inverseRelationship = inverseRelationDescription;
} else if ([inverse.name isEqualToString:relation.name]) {
newRelationship.inverseRelationship = newRelationship;
}