i have question what is best practice when using Magical Record to change some attribute for all records.
Only way, that i found is to fetch all entities in save block and after enumerate one by one. Is any better solution?
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
NSArray * devices = [CDDevice MR_findByAttribute:@"primary" withValue:@"YES" inContext:localContext];
[devices enumerateObjectsUsingBlock:^(CDDevice * device, NSUInteger idx, BOOL * _Nonnull stop) {
CDDevice * tmpDevice = [device MR_inContext:localContext];
tmpDevice.primary = @(0);
}];
} completion:^(BOOL contextDidSave, NSError *error) {
;
}];
Something like
[CDDevice MR_ChangeAtribute:"primary" toValue:@(0)];
That change for all CDDevice records change primary to YES.
That's the core data way. Fetch, change, repeat.
However, if you have lots of them to do, you should wrap it all in an autoreleasepool, and do them in small batches, and turn the objects back into faults for each batch. This prevents memory from exploding.
However, you can avoid all of that by using NSBatchUpdateRequest
.
I don't use MR, but a quick google search turned up this link, entitled "Add support for magical batch requests."
However, it looks like the commit for that set of features is relatively new (committed on Oct 10) so you will have to do some work yourself to see if it's made it into an official release or not... or if you want to use a pre-release version.