Reputation: 155
I have many child-entities which inherit properties from the same BaseEntity.
I would like to write a generic method which accepts any of the children and sets the base properties.
ChildDto *child = [[ChildDto alloc] init];
child = [BaseEntityDto SetBaseProperties:child fromDictionary:src];
The above gives the 'incompatible pointer type' error.
When I try casting the resulting BaseEntity to one of it's child classes, the cast fails and the object remains of type BaseEntity.
child = (ChildDto*)[BaseEntityDto SetBaseProperties:child fromDictionary:src];
Apparently casting is a bad idea in Objective C due to the use of pointers and there appears to be no 'dynamic' type to set as the return type.
So what's the correct way to solve this problem?
Upvotes: 0
Views: 124
Reputation: 52227
If you have no reason not to do so, you should use plain inheritance to create the objects
@interface BaseEntity : NSObject
-(instancetype)initWithProperties:(NSDictionary *) properties;
@end
@implementation BaseEntity
-(instancetype)initWithProperties:(NSDictionary *) properties
{
self = [super init];
if (self){
// apply properties for base
}
return self;
}
@end
@interface ChildDTO : BaseEntity
@end
@implementation ChildDTO
-(instancetype)initWithProperties:(NSDictionary *) properties
{
self = [super initWithProperties:properties];
if (self){
// apply properties for child
}
return self;
}
@end
Upvotes: 1
Reputation: 155
I found that if I pass in a child of BaseEntity to SetBaseProperties, set the props and return nothing, it works.
ChildDto *child = [[ChildDto alloc] init];
[BaseEntityDto SetBaseProperties:child fromDictionary:src];
// base properties of child are now set
So the signature for SetBaseProperties is:
+(void)SetBaseProperties:(BaseEntityDto *)object fromDictionary:(NSDictionary*)dictionary;
Is that a correct way of doing it?
Upvotes: 0
Reputation: 4044
Objective-C is very dynamic. Your issues may come from a lack of experience. I suggest you get familiar with the Key-Value Coding Guide: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html. It has a good chance to provide the answer to your question.
Upvotes: 0