Deleting lost objects when copying a magic record

Is there anything that is built into the magic record 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 is updated and brandCdeleted.

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

More importantly, how to remove orphaned nested objects like productBbelow

[
  { "_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" }
     ]
  }
]
+4
source share
1 answer

It turned out, but if anyone wants to call back with a better solution, please do so.

Removing orphans at "level 0" at boot

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 at level 1 in a managed entity

-(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];
}

- willImport , .

+8

Source: https://habr.com/ru/post/1544791/


All Articles