开发者

CORE DATA Many to Many relationship. How to update or set relationship?

开发者 https://www.devze.com 2023-04-11 05:50 出处:网络
I have 2 entities Locations and Items. Many to many relationship. So each item can have multiple locations and any location can have multiple items.

I have 2 entities Locations and Items. Many to many relationship.

So each item can have multiple locations and any location can have multiple items.

I'm parsing an XML of items and than trying to add locations.

So I have ManagedObject item and I have j开发者_如何学JAVAust inserted the location, so what's the syntax (code) to set the items location?

I see only add and remove in ManagedObject Class.

Is below is valid where currentItem,location are two ManagedObjects and setItem_location_relationship is the name of relationship in Items entity

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];


You should subclass your NSManagedObject. Xcode will write the class files for you. Then everything becomes easy - Xcode will generate the methods for you. Assuming your entities are called Item and Location and the to-many relationship in Item is called locations, these definitions in Item.h should look like this:

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

So to add a location object:

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号