Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@implementation NSManagedObject (TCCreation)
+ (instancetype)tc_insertIntoContext:(NSManagedObjectContext*)ctx
{
for(NSEntityDescription *desc in [ctx.persistentStoreCoordinator.managedObjectModel entities]) {
if([desc.managedObjectClassName isEqual:NSStringFromClass(self)]) {
return [[self alloc] initWithEntity:desc insertIntoManagedObjectContext:ctx];
}
}
NSAssert(NO, @"This class does not exist in the managed object model for %@", ctx);
return nil;
}
@end
extension NSManagedObject {
class func tc_insertIntoContext(context: NSManagedObjectContext) -> Self?
{
let thisClassName : String = NSStringFromClass(self as! AnyClass)
for desc in context.persistentStoreCoordinator!.managedObjectModel.entities as! [NSEntityDescription] {
if desc.managedObjectClassName == thisClassName {
return self(entity:desc, insertIntoManagedObjectContext:context)
}
}
assert(false, "This class does not exist in the managed object model for \(context)")
return nil;
}
}
@jessesquires

This comment has been minimized.

Copy link

commented Apr 17, 2015

Thanks @nevyn.

Oops, I spoke too soon on the meetup page.

So, this here will compile:

extension NSManagedObject {

    class func tc_insertIntoContext(context: NSManagedObjectContext) -> AnyObject? {
        let thisClassName : String = NSStringFromClass(self as! AnyClass)
        for desc in context.persistentStoreCoordinator!.managedObjectModel.entities as! [NSEntityDescription] {
            if desc.managedObjectClassName == thisClassName {
                return self(entity:desc, insertIntoManagedObjectContext:context)
            }
        }
        assert(false, "This class does not exist in the managed object model for \(context)")
        return nil
    }
}

There are still some major drawbacks though:

  1. Inserting a single entity is now an O(n) operation 😢
  2. Not a designated initializer
  3. We have to cast from AnyObject?
  4. This is still very "Obj-C" ish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.