aneuryzm
aneuryzm

Reputation: 64874

Emptying a Core Data NSSet (multiple relationships)

If I need to programmatically empty a NSSet automatically created by Core Data (multiple relationships), what should I do ? Something like this ?

[self willChangeValueForKey:@"MyRelationship"];

[[self MyRelationship] release];
[self MyRelationship] = [NSSet alloc] init];

[self didChangeValueForKey:@"MyRelationship"];

Not sure it is correct at all... thanks

Upvotes: 2

Views: 2745

Answers (2)

adonoho
adonoho

Reputation: 4329

Patrick,

Relations are, unsurprisingly, special in Core Data. They provide some specialized methods to remove objects from those relations. Rather than trying to override the accessors, you should use those methods. As in this snippet:

[self removeMyRelationship: self.myRelationship];

I also think your should remove your overridden accessor methods.

I have no insight into your deletion problem. I recommend that you just iterate over the group and delete the objects. I think it is important that your enumerator be a copy of your relationship. As in the following ARC code:

for (Relation *r in [self.myRelationship copy]) {

    [moc deleteObject: r];
}

Andrew

Upvotes: 1

Francis McGrew
Francis McGrew

Reputation: 7272

[[self mutableSetValueForKey:@"MyRelationship"] removeAllObjects];

For some reason, I can never get the "cascade" delete rule to work, so when I want the objects deleted as well I have to iterate over the set and call [self.managedObjectContext deleteObject:obj] or else I'll get validation errors, if the relationship is defined as required.

Upvotes: 6

Related Questions