我的應用程序中有一些代碼可以生成核心數據模型,並使用一組NSEntityDescription
來填充它。這些實體描述中的每一個都有爲其分配的任意數量的NSPropertyDescription
。這些屬性是NSAttributeDescription
s和NSRelationshipDescription
s的組合。所有關係都與現有關係相匹配,並且使用setInverseRelationship:
將它們設置爲彼此相反。CoreData:導致保存崩潰的反向關係
屬性屬性工作正常,並且多對多關係正常工作;我已經徹底測試過了。此問題似乎與NSRelationshipDescription
s有一個maxCount
值爲1,這意味着屬性說明返回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;
}
你能張貼創建模型的代碼
我通過改變創建代碼從關係固定的呢?也許簡化爲一個展示問題的最小例子? –