2013-02-04 130 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无法进行数据存储没有一些转换。