Skip to content

Instantly share code, notes, and snippets.

@nevyn
Created April 16, 2015 21:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nevyn/d22c4684370fa07078dd to your computer and use it in GitHub Desktop.
Save nevyn/d22c4684370fa07078dd to your computer and use it in GitHub Desktop.
@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
Copy link

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