Skip to content

Instantly share code, notes, and snippets.

@mlvea
Created June 2, 2016 08:51
Show Gist options
  • Save mlvea/58f999c71099ee781ff1f510aebdce22 to your computer and use it in GitHub Desktop.
Save mlvea/58f999c71099ee781ff1f510aebdce22 to your computer and use it in GitHub Desktop.
Easily duplicate CoreData objects with this universal category
//
// NSManagedObject+Duplicate.h
//
// Copyright (c) 2014 Barry Allard
//
// MIT license
//
// inspiration: https://stackoverflow.com/questions/2998613/how-do-i-copy-or-move-an-nsmanagedobject-from-one-context-to-another
#import <CoreData/CoreData.h>
@interface NSManagedObject (Duplicate)
// shallow copy of MOC ASSOCIATED object, does not update relationships
- (instancetype)duplicateAssociated;
// shallow copy of MOC UNASSOCIATED object, does not update relationships
- (instancetype)duplicateUnassociated;
@end
//
// NSManagedObject+Duplicate.m
//
// Copyright (c) 2014 Barry Allard
//
// MIT license
//
// inspiration: https://stackoverflow.com/questions/2998613/how-do-i-copy-or-move-an-nsmanagedobject-from-one-context-to-another
#import "NSManagedObject+Duplicate.h"
@implementation NSManagedObject (Duplicate)
- (void)duplicateToTarget:(NSManagedObject *)target
{
NSEntityDescription *entityDescription = self.objectID.entity;
NSArray *attributeKeys = entityDescription.attributesByName.allKeys;
NSDictionary *attributeKeysAndValues = [self dictionaryWithValuesForKeys:attributeKeys];
[target setValuesForKeysWithDictionary:attributeKeysAndValues];
}
- (instancetype)duplicateAssociated
{
NSManagedObject *result = [NSEntityDescription
insertNewObjectForEntityForName:self.objectID.entity.name
inManagedObjectContext:self.managedObjectContext];
[self duplicateToTarget:result];
return result;
}
- (instancetype)duplicateUnassociated
{
NSManagedObject *result = [[NSManagedObject alloc]
initWithEntity:self.entity
insertIntoManagedObjectContext:nil];
[self duplicateToTarget:result];
return result;
}
@end
Pod::Spec.new do |s|
s.name = 'NSManagedObject+Duplicate'
s.version = '0.0.1'
s.license = 'MIT'
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.6'
s.summary = 'Easily duplicate CoreData objects with this universal category'
s.homepage = 'https://gist.github.com/steakknife/3bae589c4da8eba9b361'
s.author = { 'Barry Allard' => 'barry.allard@gmail.com' }
s.source = { :git => 'https://gist.github.com/3bae589c4da8eba9b361.git' }
s.source_files = 'NSManagedObject+Duplicate.{h,m}'
s.frameworks = 'CoreData'
s.requires_arc = true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment