开发者

Managing NSManagedObjects

开发者 https://www.devze.com 2023-04-01 16:35 出处:网络
If I have an NSManagedObject which maintains as one of its properties a set of another type of NSManagedObject, and I set that set to nil or replace it with a different set, what happens to the manage

If I have an NSManagedObject which maintains as one of its properties a set of another type of NSManagedObject, and I set that set to nil or replace it with a different set, what happens to the managed objects in the original set? Will they be orphaned in the database? I know if you delete the parent managed object you can cascade deletes but this isn't the 开发者_Go百科same thing.

I suppose it doesn't matter if it's a set or not. If one managed object references another and now you want it to reference something different and no longer care about the old object, do you have to delete it.

I did some of my own testing:

NSSet *set = [managedObject getDefaultSet]; //at this point I can access the set
[managedObject setDefaultSet:newSet]; //at this point I can't access it anymore!

It seems that CoreData did some magic as after I replace the set with a new set, I can no longer access the old set using gdb. BUT does that mean that it's no longer in the database? I can't access it but do I also need to physically remove it from the DB?

EDIT: New test:

NSSet *set = [managedObject getDefaultSet]; //at this point I can access the set
id object = [set anyObject];
[managedObject setDefaultSet:newSet]; //at this point I can't access it anymore! BUT I can still access the object

I've verified that the object is still in existence so now I guess I do need to delete it. My guess would be to override the setDefaultSet property. What does a default mutator property look like for core data? I don't think I want to override setValue:forKey especially since the class reference tells me explicitly not to.


Here's the solution I'm going with for now:

- (void)setDefaultSet:(NSSet *)set
{
   NSMutableSet *oldSet = [self mutableSetValueForKey:@"defaultSet"];
   for (NSManagedObject *object in oldSet)
       //remove object from context
       [oldSet removeAllObjects];
   [oldSet addObjectsFromArray:[set allObjects]];
}

I added my own accessor/mutator

0

精彩评论

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

关注公众号