gpt4 book ai didi

objective-c - 核心数据 : only the last object can be initialized correctly in a loop

转载 作者:行者123 更新时间:2023-11-28 22:52:55 25 4
gpt4 key购买 nike

我的模型有两个实体 ArtistAlbumAlbum 有一个 Artist 实例成员。我使用以下代码预填充我的模型,但只发现最后一张专辑,即 ablum3,已与 Artist Beatles 建立了正确的关联。对于album1album2artist字段为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"];
}

最佳答案

没有进一步的细节,很难知道发生了什么。我试着理解你所写内容的模型。

所以,这个模型适合我

enter image description here

albums 是与 Album 的一对多关系。此外,它是可选的,您可以有 Artist 而没有 Album

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();
}
}
}

如果您需要安排您的模型,请告诉我。

希望对您有所帮助。

关于objective-c - 核心数据 : only the last object can be initialized correctly in a loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com