1

我对在 Objective-C 中使用 instancetype 感到困惑。

代码:

@interface MyClass : NSObject

-(instancetype)initWithOwner:(NSString*)anOwner;

@property (nonatomic, strong) NSString* owner;
@end


@interface MyChildClass : MyClass

-(instancetype)init;

@property (nonatomic, strong) NSString* myString;
@end

然后,我可以运行它

MyChildClass* myChildObject = [[MyChildClass alloc] initWithOwner:@"owner"];

为什么这会返回 MyChildClass 而不是 MyClass ???

为什么编译器不显示任何警告或错误消息,我正在使用超类的初始化方法,而不是 MyChildClass 初始化方法???

我在哪里可以使用这个???

4

1 回答 1

1
  1. 问题(问号 1 至 3)

这是因为instancetype. 它说:返回实例与接收者具有相同的类型(或子类)。

[[MyChildClass alloc] initWithOwner:@"owner"];

方法:

[[MyChildClass alloc] -> MyChildClass
                                      initWithOwner:@"owner"] -> MyChildClass;
  1. 问题(问号 4 至 6)

一种。Objective-C 中没有工厂方法。Objective-C 中有一些方法。

湾。编译器没有显示警告,因为一切都很好。您将引用分配给MyChildClass类型的引用变量MyChildClass

  1. 问题(问号 7 至 9)

You can use this in your example. MyChildClass can use the base' class implementation, if it does not want to change it. (Very often.)

BTW: Do you know that the returned instance is of the type MyChildClass?

于 2014-12-19T12:40:27.830 回答