我有两个实体:人物和网络(xcdatamodeld屏幕 - http://rghost.ru/47818182/image.png)。 在方法获取我提取数组人,我想打印 network.url 。
错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSFaultingMutableSet url]: unrecognized selecto
代码:
- (IBAction)insert:(id)sender
{
NSMutableSet* networks = [NSMutableSet set];
// People entity
People *people = (People *)[NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:self.managedObjectContext];
people.name = @"Alex";
people.age = @23;
// Network entity
Network *network = (Network *)[NSEntityDescription insertNewObjectForEntityForName:@"Network" inManagedObjectContext:self.managedObjectContext];
network.url = @"http://facebook.com/alex";
[networks addObject:network];
[people addNetwork:networks];
// Save
[self.managedObjectContext save:nil];
}
- (IBAction)fetch:(id)sender
{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"People"];
NSArray *peoples = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (People *people in peoples)
{
Network *network = (Network *)people.network;
NSLog(@"%@", network.url);
}
}
答案 0 :(得分:0)
“人物 - >>网络”是 to-many 关系,因此people.network
是网络对象的集,而不是单个网络对象。
以下应该有效:
for (People *people in peoples)
{
for (Network *network in people.network)
{
NSLog(@"%@", network.url);
}
}
答案 1 :(得分:0)
因为人与网络之间的关系太多了。因此,如果您查看ManagedObject
类People
,您的对象将返回NSSet。所以你的循环应该是这样的。
for (People *people in [peoples allObjects])
{
Network *network = (Network *)people.network;
NSLog(@"%@", network.url);
}