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" }
]
}
]
Figured it out but would if anyone would like to chime in with a better solution please do so.
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];
-(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With