如何提取核心数据中的数据关系?

时间:2013-08-01 10:01:38

标签: core-data

我有两个实体:人物和网络(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);
    }
}

2 个答案:

答案 0 :(得分:0)

“人物 - >>网络”是 to-many 关系,因此people.network 是网络对象的,而不是单个网络对象。 以下应该有效:

for (People *people in peoples)
{
    for (Network *network in people.network)
    {
        NSLog(@"%@", network.url);
    }
}

答案 1 :(得分:0)

因为人与网络之间的关系太多了。因此,如果您查看ManagedObjectPeople,您的对象将返回NSSet。所以你的循环应该是这样的。

for (People *people in [peoples allObjects])
{
    Network *network = (Network *)people.network;
    NSLog(@"%@", network.url);
}