Objective c 目标c返回动态类型的方法

Objective c 目标c返回动态类型的方法,objective-c,Objective C,我有许多子实体,它们从同一BaseEntity继承属性 child = (ChildDto*)[BaseEntityDto SetBaseProperties:child fromDictionary:src]; 我想写一个通用方法,它接受任何子类并设置基本属性 ChildDto *child = [[ChildDto alloc] init]; child = [BaseEntityDto SetBaseProperties:child fromDictionary:src]; 上面给出了

我有许多子实体,它们从同一BaseEntity继承属性

child = (ChildDto*)[BaseEntityDto SetBaseProperties:child fromDictionary:src];
我想写一个通用方法,它接受任何子类并设置基本属性

ChildDto *child = [[ChildDto alloc] init];
child = [BaseEntityDto SetBaseProperties:child fromDictionary:src];
上面给出了“不兼容指针类型”错误

当我尝试将结果BaseEntity强制转换为它的一个子类时,转换失败,对象仍然是BaseEntity类型

child = (ChildDto*)[BaseEntityDto SetBaseProperties:child fromDictionary:src];
显然,由于使用指针,在Objective C中强制转换是一个坏主意,而且似乎没有“动态”类型设置为返回类型


那么解决这个问题的正确方法是什么呢

Objective-C非常动态。你的问题可能来自缺乏经验。我建议您熟悉键值编码指南:。它很有可能为您的问题提供答案。

我发现,如果我将BaseEntity的子级传递给SetBaseProperties,设置道具,但不返回任何内容,那么它会起作用

ChildDto *child = [[ChildDto alloc] init];
[BaseEntityDto SetBaseProperties:child fromDictionary:src];
// base properties of child are now set
因此,SetBaseProperties的签名为:

+(void)SetBaseProperties:(BaseEntityDto *)object fromDictionary:(NSDictionary*)dictionary;

这是正确的方法吗?

如果没有理由不这样做,那么应该使用普通继承来创建对象

@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

我认为你所做的应该是有效的;请显示一些代码。如果所有子类都来自同一个基本实体,并且您只想设置基本属性,请创建一个接受基本实体类作为参数的方法。来自c#以上内容对我来说非常有意义。但是它不起作用-添加了一些代码来帮助解释。
SetBaseProperties
方法的返回类型是什么?如果它是
BaseEntityDto
ChildDto
的某个其他超类,则需要强制转换到该子类。C++、java和C++中也一样。如果
SetBaseProperties
实际上没有将
childt的实例返回到
,则您还有其他问题。SetBaseProperties返回一个BaseEntity-但对子实例的强制转换无法更改实例类型Yep,你是对的,ObjC对我来说是新的:)这看起来像是一个不错的读物-但希望能有一个快速的指针让我在晚上越过这个障碍。你为什么不让
BaseEntity
有一个
-initWithProperties:
,在那里设置基本属性并覆盖它,以便将
ChildeDto
中的属性设置为
并从那里调用基本实现?在我阅读了上面的评论之后,我刚刚键入了一些类似的内容,你抢先告诉我:)这更干净了。谢谢