Obtain the NSEntityDescription of an NSManagedObject from a class method

795 views Asked by At

I'm adding a few class methods to NSManagedObject and in one of them I need to obtain the NSEntityDescription of it. Problem is, entity is an instance method and I don't know how to access it from a class method.

Is there any way of doing this, short of creating a dummy instance just for accessing this property? Sounds like a horrible hack...

1

There are 1 answers

2
Danny S On

NSManagedObject class can't know about NSEntityDescription simply because there's no entity at class level. Look at - (instancetype)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context; after you initialise it with an entity description you will be able to retrieve it, from an instance of course.

One way to achieve what you are describing would be having a NSManagedObject subclass for your Core Data entity (which is a recommended approach) and having a class method + (NSString)entityName which will return a string representing the entity name in your Core Data model.

+ (NSString *)entityName {
    return @"MyEntity";
}

If we assume that the class name and the entity name are the same you could do:

+ (NSString *)entityName {
    return NSStringFromClass(self);
}

Hope it helps.