Skip to content

Instantly share code, notes, and snippets.

@drumnkyle
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drumnkyle/eb9a36aac5f186cd76c7 to your computer and use it in GitHub Desktop.
Save drumnkyle/eb9a36aac5f186cd76c7 to your computer and use it in GitHub Desktop.
Trying to rewrite a category on NSManagedObject in Swift
// Objective-C
@implementation NSManagedObject (Helpers)
+ (instancetype)createEntity
{
id newObject = [NSEntityDescription
insertNewObjectForEntityForName:[[self class] description]
inManagedObjectContext:[[SACoreDataStack defaultStack]
managedObjectContext]];
return newObject;
}
@end
// Swift
extension NSManagedObject {
class func createEntity() -> Self {
return NSEntityDescription.insertNewObjectForEntityForName(self.description(),
inManagedObjectContext: CoreDataStack.defaultStack.managedObjectContext)
// Error on the above line: "'AnyObject' is not convertible to 'Self'"
}
}
@ethereal-engineer
Copy link

Any issue with using AnyObject as the return type?

@seanwoodward
Copy link

@iosengineer I think it would be nice to wrap the requisite type casting in the factory method implemented as an extension of NSManagedObject and not on each subclass. Have any thoughts on how to approach this using generics?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment