1

I`m new with Core Data and I face some problems with Many-To-Many relationships,

Here is my structure

Diagrams

This structure allow that 1 Profile can have many itens and 1 Item can be in many Profiles It`s like a Store

Both relations is Inverse

So when I`m add a new Item in Profile, the new Item was duplicate in my table Item.

ITENS LIST
========== 
ITEM9
ITEM50
==========

after add a new Item in Profile

ITENS LIST
==========
ITEM9
ITEM50
ITEM9
==========

When I list my profile "itens" is correct just 1 new Item.

PROFILE 
========== 
ITEM9 
==========

My code for this operations is.

MocManager* moc = [MocManager sharedMocManager];
NSArray* products = [moc listData:@"products"];
NSMutableString* desc = [NSMutableString string];

if( products != nil ) {
    Item* itemToBuy = products[0]; // This is just a test. get the first
    Item* newItem = [Item initItem];

    NSEntityDescription *entity = [itemToBuy entity];
    for (NSString *attributeName in [entity attributesByName]) {
        [newItem setValue:[itemToBuy valueForKey:attributeName] forKey:attributeName];
    }
    for (NSString *relationshipName in [entity relationshipsByName]) {
        [newItem setValue:[itemToBuy valueForKey:relationshipName] forKey:relationshipName];
    }


    [desc appendString:newItem.identifier];

    [profile addItensObject:newItem];

    [moc saveData];
}

My question is.

  • Can I prevent the duplication ?

  • If its not possible to prevent this. How can I list only Itens that dosen`t have any Profile associated ?

Tks

Brunno

4

1 回答 1

1

这是我检查重复项的方法:

ENTITY* obj = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ENTITY"];
request.predicate = [NSPredicate predicateWithFormat:@"ENTITY.ID = %@", NEW_ELEMENT_ID];

NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];

if (!matches || ([matches count] > 1)) {
    //NSLog(@"Error, YOU HAVE MORE THAN ONE OBJECT WITH SAME ID");
} else if ([matches count] == 0) {
    //NSLog(@"NEW, OBJ NOT FOUND WITH THAT ID");
    obj = [NSEntityDescription insertNewObjectForEntityForName:@"ENTITY" inManagedObjectContext:YOUR_CONTEXT];
} else {
    obj = [matches lastObject]; //only one obj found... update this one
}

return obj;
于 2014-01-29T17:39:56.290 回答