【问题标题】:CORE DATA Many to Many relationship. How to update or set relationship?核心数据 多对多关系。如何更新或设置关系?
【发布时间】:2011-12-01 21:13:53
【问题描述】:

我有 2 个实体 Locations 和 Items。多对多关系。

所以每个项目可以有多个位置,任何位置都可以有多个项目。

我正在解析项目的 XML,而不是尝试添加位置。

所以我有 ManagedObject 项目并且我刚刚插入了位置,那么设置项目位置的语法(代码)是什么?

我只看到在 ManagedObject 类中添加和删除。

以下是有效的 其中 currentItem,location 是两个 ManagedObjects,setItem_location_relationship 是 Items 实体中的关系名称

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Locations"
                                                  inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"location_id = %@",
                                  [locationsArray objectAtIndex:i]];
        [fetchRequest setPredicate:predicate];

        NSError *error = nil;
        NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {

        }

        [fetchRequest release];

        Locations *location = [fetchedObjects objectAtIndex:0];

        NSSet *set = [NSSet setWithObject:location];

        [currentItem setItem_location_relationship:set];

【问题讨论】:

    标签: core-data many-to-many entity-relationship nsmanagedobject nsmanagedobjectcontext


    【解决方案1】:

    你应该继承你的NSManagedObject。 Xcode 将为您编写类文件。然后一切都变得简单——Xcode 会为你生成方法。假设您的实体称为ItemLocationItem 中的多对多关系称为locationsItem.h 中的这些定义应如下所示:

    - (void)addLocationsObject:(NSManagedObject *)value;
    - (void)removeLocationsObject:(NSManagedObject *)value;
    - (void)addLocations:(NSSet *)values;
    - (void)removeLocations:(NSSet *)values;
    

    所以要添加一个位置对象:

    Location *loc = [NSEntityDescription insertNewObjectForEntityForName:"Location"
       inManagedObjectContext:self.managedObjectContext];
    // ... configure loc with info from the xml feed
    // or use a fetched location object
    [currentItem addLocationsObject:loc];
    

    【讨论】:

    • 是的,我有这些方法。但我的问题是我如何将现有位置实际设置为我创建的项目。
    • 我的意思是不想添加 Location ,如果已经存在怎么办,所以我想把item链接到现有的位置。还是它确实是这样做的?
    • 对,这正是它的作用。它只是在实体的现有实例之间建立链接(“关系”)。
    • 感谢您的帮助并回答了我所有的问题
    • @tristan 您需要设置模型,然后生成托管对象类文件 - 方法将自动生成。
    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2016-09-08
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多