代码之家  ›  专栏  ›  技术社区  ›  Julian F. Weinert

Objective-C类方法返回父类对象

  •  1
  • Julian F. Weinert  · 技术社区  · 11 年前

    我正在尝试将属性添加到 UIBezierPath 。所以我创建了一个子类 JWBezierPath 。我想让所有的类方法shorthands也带有数字参数,所以我创建了这些方法:

    + (JWBezierPath *)bezierPathWithColor:(UIColor *)color {
        JWBezierPath *path = [self bezierPath];
        [path setColor:color];
        return path;
    }
    

    问题是 [self bezierPath] 确实返回的实例 UI边框路径 而不是我的子类。我还尝试使用混凝土类: [JWBezierPath bezierPath]

    我该如何解决这个问题?

    2 回复  |  直到 11 年前
        1
  •  1
  •   Vladimir    11 年前

    如果您不执行 +bezierPath 方法,那么将调用超类实现,它将创建UIBezierPath的实例,而不是JWBezierPath。

    理论上,基类中的工厂方法可以创建实例,即使这些方法不会被重写,例如,考虑BaseClass中工厂方法的两个选项:

    // Will create instance of child class even if method won't be overriden
    + (instancetype) someObject {
       return [self new];
    }
    

    // Will always create instance of base class
    + (BaseClass*) someObject {
       return [BaseClass new];
    } 
    

    然而,考虑到 +边框路径 声明( +(UIBezierPath *)bezierPath )并且您的证据UIBezierPath类不是以这种方式实现的,您必须实现 +边框路径 幼崽课堂中的方法

        2
  •  1
  •   Arek Holko    11 年前

    bezierPath 定义为:

    + (UIBezierPath *)bezierPath
    

    因此,您可能需要使用:

    JWBezierPath *path = [[self alloc] init];
    

    相反

    推荐文章