0

I am trying to write a convenience method for creating new object types in CoreData. I have my managedObjectContext defined at global level in another file.

This is what my code looks like:

class Room: NSManagedObject {

    class func createNew() -> NSManagedObject {
        return NSEntityDescription.insertNewObjectForEntityForName("Room", inManagedObjectContext: managedObjectContext!) as? NSManagedObject
    }
}

Where I am calling managedObjectContext I get an error. It says

Room.Type does not have a property named managedObjectContext

Yet that is not where I want to look for this data. It even appears in the auto-complete correctly and then only breaks after completing.

Julian E.
  • 4,687
  • 6
  • 32
  • 49
Mathieson
  • 1,194
  • 2
  • 13
  • 28
  • 1
    This might also interest you in this context: [How can I create instances of managed object subclasses in a NSManagedObject Swift extension?](http://stackoverflow.com/questions/27109268/how-can-i-create-instances-of-managed-object-subclasses-in-a-nsmanagedobject-swi). – Martin R Jun 14 '15 at 18:24
  • That is great. That is actually exactly what I was wanting to do, but was in the process of figuring it out for myself. Thanks for the shortcut :) – Mathieson Jun 15 '15 at 06:21

1 Answers1

1

The problem is that NSMangedObject has an instance property with the same name managedObjectContext (which you of course cannot access from a type method).

Renaming the global variable should solve the problem, or you can refer to it with the explicit module name of your app:

YourAppModuleName.managedObjectContext
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • You are welcome! – Actually I don't know if this is not a bug in the compiler, so you might consider to file a bug report. – Martin R Jun 14 '15 at 18:31