如何在核心数据中插入和获取多个关系实体

时间:2015-12-16 07:03:11

标签: ios objective-c core-data

我需要一个示例代码,如何以一对多关系保存和获取数据?这是我的两个NSManagedObject子类。我设法进行保存并获取一对一的关系。

1 个答案:

答案 0 :(得分:0)

数据保存代码

UserDefinedInterests *aAserDefineInterrest1 = [NSEntityDescription insertNewObjectForEntityForName:@"UserDefinedInterests" inManagedObjectContext:context];

aAserDefineInterrest1.name = @"PPP";
aAserDefineInterrest1.categoryId = [NSNumber numberWithInt:168004];

UserDefinedInterests *aAserDefineInterrest2 = [NSEntityDescription insertNewObjectForEntityForName:@"UserDefinedInterests" inManagedObjectContext:context];

aAserDefineInterrest2.name = @"QQQ";
aAserDefineInterrest2.categoryId = [NSNumber numberWithInt:12248004];

UserDefinedInterests *aAserDefineInterrest3 = [NSEntityDescription insertNewObjectForEntityForName:@"UserDefinedInterests" inManagedObjectContext:context];

aAserDefineInterrest3.name = @"RRR";
aAserDefineInterrest3.categoryId = [NSNumber numberWithInt:3534535];

NSMutableSet *userDefineInterests = [NSMutableSet setWithObjects:aAserDefineInterrest, nil];

[aTopic addUserDefinedInterests:userDefineInterests];

数据提取代码

// Test listing topic details from the store
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (TopicDetails *aTopic in fetchedObjects) {

    ......

    NSSet *pp = aTopic.userDefinedInterests;

    for (some *somearray in pp.allObjects) {


    }
}