Reputation: 9813
I have an object Car.h. Car.h has carparts.h (NSSet to relationship).
I need to delete one of the parts in the NSSet belonging to car.h object.
How do I do this?
Upvotes: 7
Views: 11343
Reputation: 1376
Just another alternate way of deleting object in NSSet from core Data is using below. I tried this approach myself and it works also.
- (void)removeCarpartsObject:(Carpart *)value
{
NSError *error;
NSInteger index = [car.mySet.allObjects indexOfObject:carpartsObject];
[self.managedObjectContext deleteObject:car.mySet.allObjects[index]];
[self.managedObjectContext save:&error];
}
Upvotes: 0
Reputation: 23278
If car.mySet
is your set, you can try it as,
NSMutableSet *mutableSet = [car.mySet mutableCopy];
[mutableSet removeObject:carpartsObject];
car.mySet = [mutableSet copy];
Upvotes: 18
Reputation: 173542
If you want to make sure the to-many object is also removed from the object storage (the default action is to nullify the parent entity), you can override one of the auto-generated methods of Car
:
- (void)removeCarpartsObject:(Carpart *)value
{
NSMutableSet *set = [self mutableOrderedSetValueForKey:NSStringFromSelector(@selector(carparts))];
[set removeObject:value];
[self.managedObjectContext deleteObject:value];
}
Upvotes: 0
Reputation: 8664
I'm assuming that Car
is a subclass of NSManagedObject
since you have the core-data tag.
Core Data is KVO compliant.
Reference here
Dynamically-Generated Accessor Methods
By default, Core Data dynamically creates efficient public and primitive get and set accessor methods for modeled properties (attributes and relationships) of managed object classes. This includes the key-value coding mutable proxy methods such as add<Key>Object:
and removes:, as detailed in the documentation for mutableSetValueForKey:—managed objects are effectively mutable proxies for all their to-many relationships.
Other Reference here about naming convention for KVO
In order to be key-value coding complaint for a mutable unordered to-many relationship
you must implement the following methods:
-add<Key>Object: or -add<Key>:
. At least one of these methods must be implemented. These are analogous to the NSMutableSet method addObject:.
-remove<Key>Object: or -remove<Key>:
. At least one of these methods must be implemented. These are analogous to the NSMutableSet method removeObject:.
-intersect<Key>:
. Optional. Implement if benchmarking indicates that performance is an issue. It performs the equivalent action of the NSSet method intersectSet:.
Upvotes: 4