我在以下关系中设置了两个对象:
新闻< - >>链路
链接包含两个属性,其中一个是URL,另一个是关联文本。我最初创建了新闻并用信息填充它:
NSManagedObject *newsData = [NSEntityDescription
insertNewObjectForEntityForName:@"News"
inManagedObjectContext:context];
[newsData setValue:[object objectForKey:@"username"] forKey:@"username"];
[newsData setValue:message forKey:@"content"];
[newsData setValue:[object objectForKey:@"when"] forKey:@"date"];
[newsData setValue:imgUrl forKey:@"img"];
NSMutableSet *links = [launchTicker mutableSetValueForKey:@"links"];
然后在for循环中,我创建一个Link:
NSManagedObject *linkInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"Link"
inManagedObjectContext:context];
[linkInfo setValue:[object objectForKey:@"id"] forKey:@"id"];
[linkInfo setValue:[[item firstChild] content] forKey:@"text"];
[linkInfo setValue:[[item attributes] valueForKey:@"href"] forKey:@"url"];
[links addObject:linkInfo];
完成for循环后,我将我创建的Link集创建为News对象:
[newsData setValue:links forKey:@"links"];
当我获取数据时,我可以获取新闻的信息,但是当我获取链接时,我什么也得不回来:
for (NSManagedObject *info in fetchedObjects) {
[fetchRequest setReturnsObjectsAsFaults:NO];
[fetchRequest setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"links", nil]];
NSMutableArray *url = [[NSMutableArray alloc] init];
NSMutableArray *text = [[NSMutableArray alloc] init];
NSSet* links = [info valueForKey:@"links"];
NSArray *arrayLinks = [links allObjects];
for(NSManagedObject *link in arrayLinks) {
[url addObject:[link valueForKeyPath:@"url"]];
[text addObject:[link valueForKeyPath:@"text"]];
}
当我尝试访问我的相关对象时,有人可以告诉我为什么我会找回0个对象吗?
答案 0 :(得分:1)
为什么不使用
NSSet *setOfLinks = newsObject.links;
答案 1 :(得分:0)
我用以下代码解决了它:
NSEntityDescription *linkEntity = [NSEntityDescription entityForName:@"Link"inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY id == %@", [info valueForKey:@"id"]];
[fetchRequest setEntity:linkEntity];
[fetchRequest setPredicate:predicate];
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];