Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove orphaned objects on magical record import

Is there anything built into magicalrecord to handle orphans? For example, if I load the following JSON data...

[
  { "_id"   : "b1", "name"  : "brandA"},
  { "_id"   : "b2", "name"  : "brandB"},
  { "_id"   : "b3", "name"  : "brandC"}
]

Then the data gets updated and brandC gets removed

[
  { "_id"   : "b1", "name"  : "brandA"},
  { "_id"   : "b2", "name"  : "brandB"}
]

More importantly, how would one delete orphaned nested objects such as productB below

[
  { "_id"   : "b1", 
    "name"  : "brandA"
    "products" : [
        {"_id" : "p1", "name" : "productA" },
        {"_id" : "p2", "name" : "productB" }
     ]
  },
  { "_id"   : "b2", 
    "name"  : "brandB"
    "products" : [
        {"_id" : "p3", "name" : "productC" },
        {"_id" : "p4", "name" : "productD" }
     ]
  }
]
like image 294
glued Avatar asked Jun 16 '14 18:06

glued


1 Answers

Figured it out but would if anyone would like to chime in with a better solution please do so.

Removing orphans on "Level 0" on load

NSArray *newdata   =  [];//AN ARRAY OF NEW DATA
NSArray *idList         = [newdata valueForKey:@"_id"];
NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"NOT(_id IN %@)", idList];
[MRBrand MR_deleteAllMatchingPredicate:predicate];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

Removing nested orphans on "Level 1" within the managed object

-(void)willImport:(id)data{
    NSArray *idList         = [data[@"products"] valueForKey:@"_id"];
    NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"NOT(pid IN %@) AND brand.bid == %@", idList, self.bid];
    [Product MR_deleteAllMatchingPredicate:predicate inContext:self.managedObjectContext];
}

On the Brand Entity in willImport we're searching for product ids that dont match the new data and removing them.

like image 143
glued Avatar answered Oct 06 '22 11:10

glued