NSManagedObjectのコピー

NSManagedObjectのコピー

Shallow copy

レーションのコピーは動作未確認

- (id)copy
{
	NSEntityDescription *entity = [self entity];
	NSArray *properties = [entity properties];
	NSEnumerator *enumerator = [properties objectEnumerator];
	id newObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:[self managedObjectContext]];
	id property;
	NSString *key;
	while(property = [enumerator nextObject]) {
		if ([property isKindOfClass:[NSAttributeDescription class]]) {
			key = [property name];
			[newObject setValue:[self valueForKey:key] forKey:key];
		}
		else
		if ([property isKindOfClass:[NSRelationshipDescription class]]) {
			key = [property name];
			if ([property isToMany]) {
				[[newObject mutableSetValueForKey:key] addObjectsFromArray:[[self mutableSetValueForKey:key] allObjects]];
			} else {
				[newObject setValue:[self valueForKey:key] forKey:key];
			}
		}
	}
	return newObject;
}