2013-02-04 115 views
0

我遇到了我在CoreData中設置的關係問題。它的一對多,一個客戶可以有很多聯繫,這些聯繫人來自地址簿。保存一對多的關係CoreData

我的模型,它看起來像這樣:

Customer <---->> Contact 
Contact <-----> Customer 

Contact.h

@class Customer; 

@interface Contact : NSManagedObject 

@property (nonatomic, retain) id addressBookId; 
@property (nonatomic, retain) Customer *customer; 

@end 

Customer.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' 

任何建議,將不勝感激。

+0

在您的數據模型中如何配置'addressBookId'?您使用的是什麼核心數據類型? Contact.m是否具有此屬性的任何自定義設置代碼? –

+0

一種可能性是您設置了與您的數據模型上聲明的值不同類型的'value'屬性 – Yaman

+0

@TomHarrington Contact.m沒有任何自定義代碼。數據模型中的'addressBookId'是'Transformable'。 –

回答

3

問題是addressBookId(如您在評論中提到的那樣)定義爲Contact實體上的可變形屬性。然而(正如您在評論中提到的那樣),您沒有任何自定義代碼來實際將ABRecordRef轉換爲Core Data知道如何存儲的內容。如果沒有自定義轉換器,Core Data將嘗試通過調用值encodeWithCoder:來轉換該值。但ABRecordRef不符合NSCoding,所以此失敗,您的應用程序崩潰。

如果要將ABRecordRef存儲在覈心數據中,則需要創建NSValueTransformer子類並在數據模型中對其進行配置。您的變壓器需要將ABRecordRef轉換爲Core Data知道的其中一種類型。我沒有使用地址簿API足以提供有關此詳細信息的建議,但Apple文檔NSValueTransformer相當不錯。

它是一對多關係的事實是不相關的;問題是ABRecordRef無法進行數據存儲沒有一些轉換。