我在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
未经转换就无法进入您的数据存储。
关于ios - 保存一对多关系CoreData,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14696228/