Stanislav Pankevich
Stanislav Pankevich

Reputation: 11368

The best way to know an instance type from a class method of the same class?

I want to learn how to make class methods to return instancetype values instead of id.

Simple demonstration:

@implementation MyGenericManagedObject
+ (instancetype)existingObjectByObjectID:(NSManagedObjectID *)objectID {
    return (__typeof([self alloc]))[managedObjectContext() existingObjectWithID:objectID error:nil];
}

Having this method written this way, it does work, but if I remove (__typeof([self alloc])) I begin getting "Incompatible pointer types casting 'NSManagedObject *' to type 'MyGenericManagedObject *'.

What is the right way to get instance type from inside a class method of the same class?

Upvotes: 2

Views: 235

Answers (2)

Sulthan
Sulthan

Reputation: 130102

@implementation MyGenericManagedObject
+ (instancetype)existingObjectByObjectID:(NSManagedObjectID *)objectID {
    return (id)[managedObjectContext() existingObjectWithID:objectID error:nil];
}

Just casting to id should work.

Upvotes: 1

bbum
bbum

Reputation: 162712

existingObjectWithID:error: is explicitly typecast to return NSManagedObject*. That, frankly, is a bug in the API and you should file it.

Because of that, you'll need the cast.

Upvotes: 2

Related Questions