我的模型有两个实体Artist
和Album
,而Album
有一个Artist
实例成员。我使用以下代码预先填充我的模型,但只找到最后一个相册,即ablum3
,已与Artist Beatles
建立了正确的关联。对于album1
,album2
,artist
字段为nil
。
一定有什么不对的,我没有发现......
//create an artist
NSManagedObject *artist = [NSEntityDescription
insertNewObjectForEntityForName:@"Artist"
inManagedObjectContext:__managedObjectContext];
[artist setValue:@"Beatles" forKey:@"name"];
//populate the data
NSArray *albums = [NSArray arrayWithObjects:@"album1",@"album2",@"album3", nil];
for (NSString *title in albums){
//populate the data
NSManagedObject *album = [NSEntityDescription
insertNewObjectForEntityForName:@"Album"
inManagedObjectContext:__managedObjectContext];
[album setValue:title forKey:@"title"];
[album setValue:artist forKey:@"artist"];
}
答案 0 :(得分:2)
没有进一步的细节,很难知道发生了什么。我试着理解你所写的模型。
所以,这个模型适合我
albums
是与Album
的多对多关系。此外,它是可选的,您可以Artist
没有Album
。
artist
是艺术家的反向rel。一对一的基数。这是必需的,因为如果没有Album
,则无法Artist
。
这里是代码:
- (void)populateDB
{
//create an artist
NSManagedObject *artist = [NSEntityDescription
insertNewObjectForEntityForName:@"Artist"
inManagedObjectContext:[self managedObjectContext]];
[artist setValue:@"Beatles" forKey:@"name"];
//populate the data
NSArray *albums = [NSArray arrayWithObjects:@"album1",@"album2",@"album3", nil];
for (NSString *title in albums){
//populate the data
NSManagedObject *album = [NSEntityDescription
insertNewObjectForEntityForName:@"Album"
inManagedObjectContext:[self managedObjectContext]];
[album setValue:title forKey:@"title"];
[album setValue:artist forKey:@"artist"];
}
}
调用populatedDB
后,保存调用[self saveContext]
- (void)saveContext {
NSError *error = nil;
NSManagedObjectContext *moc = [self managedObjectContext];
if (moc != nil) {
if ([moc hasChanges] && ![moc save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
如果您需要安排模型,请告诉我。
希望有所帮助。