我的模型有两个实体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"];
}发布于 2012-07-14 22:02:46
如果没有进一步的细节,就很难知道发生了什么。我试着理解你所写的模型。
所以,这个模型适用于我。

与Album相比,albums是一种多对关系。此外,它是可选的,您可以使用不带Album的Artist。
artist是艺术家的反向版本。一对一基数。它是必需的,因为没有Artist就不能有Album。
代码如下:
- (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();
}
}
}如果你需要安排你的模型,请告诉我。
希望这能有所帮助。
https://stackoverflow.com/questions/11484075
复制相似问题