我有 2 个实体。 1 称为 WishListElement 和其他 WishListContainer。
-(BOOL)addElementToWishList:(WishListElement*)element
{
ASAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
_managedObjectContext = [appDelegate managedObjectContext];
WishListElement *wishList = [NSEntityDescription insertNewObjectForEntityForName:@"WishListElement" inManagedObjectContext:_managedObjectContext];
[wishList setAppName: element.appName];
[wishList setAppPrice: element.appPrice];
[wishList setAppCategory: element.appCategory];
[wishList setAppSummary: element.appSummary];
[wishList setAppCopyright:element.appCopyright];
[wishList setAppAuthor: element.appAuthor];
[wishList setAppImage:element.appImage];
NSError *error = nil;
[_managedObjectContext save:&error];
WishListContainer *wishListContainer = [NSEntityDescription insertNewObjectForEntityForName:@"WishListContainer" inManagedObjectContext:_managedObjectContext];
[wishListContainer addContainsObject:wishList];
if (![_managedObjectContext save:&error])
{
return NO;
}
else
{
return YES;
}
}
-(NSMutableArray*)getWishListElement
{
ASAppDelegate *appDelegate = (ASAppDelegate*) [[UIApplication sharedApplication]delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"WishListContainer" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *fetchRequest = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];
[self setWishListArray:fetchRequest];
WishListContainer *container = [fetchRequest objectAtIndex:0];
NSLog(@"%d",container.contains.count);
return [container.contains.allObjects mutableCopy];
}
但问题是,当我尝试使用上述代码显示心愿单内容时,它显示的是一个空 TableView 。
WishListContainer *container = [fetchRequest objectAtIndex:0];
NSLog(@"%d",container.contains.count);
return [container.contains.allObjects mutableCopy];
以上几行都显示为0,请帮帮我。
最佳答案
首先,创建一个反向关系。如此处所述 https://stackoverflow.com/a/764572/3429577这是数据完整性所必需的。
关于ios - 从核心数据中一对多关系中的实体获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117006/