Reputation: 625
I have a category for NSManagedObjectContext
, which inserts an NSManagedObject
in another NSManagedObjectContext
and returns item:
@implementation NSManagedObjectContext (GTEntity)
- (id)addEntity:(id)entity {
NSManagedObject *entityObject = [self objectWithID:[entity objectID]];
return entityObject;
}
@end
My question is how I return object the same type as I've got. I mean, if I call [ctx addEntity:city]
with City *city
, where the City is a NSManagedObject
subclass, I would like to get the object in other context but the same type, not in NSManagedObject
type. This type is generic and should be determinated at the runtime from entity, like objc_getClass(entity)
. I found some macros, but it has some strange errors Expected "]"
after (cls *)
:
#define objc_dynamic_cast(obj, cls) \
([obj isKindOfClass:(Class)objc_getClass(#cls)] ? (cls *)obj : NULL)
Upvotes: 1
Views: 322
Reputation: 9030
Just do City *city = [someManagedObjectContext addEntity:someCityObject];
assuming City
derives from NSManagedObject
. Your return variable will have been dynamically casted. Though I don't believe there is anything to be gained from making a category out of it, you could just do it directly like so:
City *city = [someManagedObjectContext objectWithID:[someCityObject objectID]];
Upvotes: 1