从核心数据中的一对多关系中获取实体中的数据

时间:2014-09-30 09:14:25

标签: ios iphone core-data

我有2个实体。 1名为WishListElement和其他WishListContainer。

CoreData

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

但问题是,当我尝试使用上面的代码显示心愿单内容时,它会显示一个空表视图。

WishListContainer *container = [fetchRequest objectAtIndex:0];
NSLog(@"%d",container.contains.count);
return [container.contains.allObjects mutableCopy];

以上几行显示为0.请帮帮我。

1 个答案:

答案 0 :(得分:1)

首先,创建一个反向关系。正如此处https://stackoverflow.com/a/764572/3429577所解释的那样,数据完整性是必要的。