[英]Saving one-to-many relationship CoreData
我在CoreData中設置的關系遇到麻煩。 它一對多,一個客戶可以有多個聯系人 ,這些聯系人來自通訊錄。
我的模型看起來像這樣:
Customer <---->> Contact
Contact <-----> Customer
聯絡人
@class Customer;
@interface Contact : NSManagedObject
@property (nonatomic, retain) id addressBookId;
@property (nonatomic, retain) Customer *customer;
@end
客戶.h
@class Contact;
@interface Customer : NSManagedObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *contact;
@end
@interface Customer (CoreDataGeneratedAccessors)
- (void)addContactObject:(Contact *)value;
- (void)removeContactObject:(Contact *)value;
- (void)addContact:(NSSet *)values;
- (void)removeContact:(NSSet *)values;
@end
並嘗試保存:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
Customer *customer = (Customer *)[NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:context];
[customer setValue:name forKey:@"name"];
for (id contact in contacts) {
ABRecordRef ref = (__bridge ABRecordRef)(contact);
Contact *contact = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:context];
[contact setValue:(__bridge id)(ref) forKey:@"addressBookId"];
[customer addContactObject:contact];
}
NSError *error;
if ([context save:&error]) { // <----------- ERROR
// ...
}
用我的代碼,我有此錯誤:
-[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x9c840c0
*** -[NSKeyedArchiver dealloc]: warning: NSKeyedArchiver deallocated without having had -finishEncoding called on it.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x9c840c0'
任何建議,將不勝感激。
問題在於(如您在評論中所述) addressBookId
被定義為Contact
實體上的可轉換屬性。 但是(正如您在評論中也提到的那樣),您沒有任何自定義代碼將ABRecordRef
實際轉換為Core Data知道如何存儲的內容。 在沒有自定義轉換器的情況下,Core Data將嘗試通過在值上調用encodeWithCoder:
來嘗試轉換值。 但是ABRecordRef
不符合NSCoding
,因此失敗了,您的應用程序崩潰了。
如果要將ABRecordRef
存儲在Core Data中,則需要創建一個NSValueTransformer
子類並在數據模型中對其進行配置。 您的轉換器需要將ABRecordRef
轉換為Core Data知道的一種類型。 我還沒有使用足夠的地址簿API來提供有關此細節的建議,但是Apple很好地記錄了NSValueTransformer
。
這是一對多關系這一事實無關緊要; 問題是ABRecordRef
如果不進行一些轉換就無法進入您的數據存儲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.