子类继承类工厂方法(Objective-C)的问题



虽然我对C#非常熟悉,但我对Objective C和iOS开发完全陌生。 所以我正在学习语言。 我不明白的是为什么以下代码会抛出编译器错误(是的,这是来自使用目标 C 编程的练习:

SNDPerson:

@interface SNDPerson : NSObject
@property NSString *first;
@property NSString *last;
+ (SNDPerson *)person;
@end
@implementation SNDPerson
+ (SNDPerson *)person
{
   SNDPerson *retVal = [[self alloc] init];
   retVal.first = @"Ari";
   retVal.last = @"Roth";
   return retVal;
}
@end

SNDShoutingPerson:

#import "SNDPerson.h"
@interface SNDShoutingPerson : SNDPerson
@end
@implementation SNDShoutingPerson
// Implementation is irrelevant here; all it does is override a method that prints a string
// in all caps.  This works; I've tested it.  However, if necessary I can provide more code.
// The goal here was for a concise repro.
@end

主要方法:

- int main(int argc, const char * argv[])
{
   SNDShoutingPerson *person = [[SNDShoutingPerson alloc] person];  // Error
   ...
}

错误是"SNDShoutingPerson"没有可见@interface声明选择器"person"。

这不应该行吗? SNDShoutingPerson 继承自 SNDPerson,所以我假设它可以访问 SNDPerson 的类工厂方法。 我在这里做错了什么,还是我也必须在SNDShoutingPerson的接口上声明该方法? 练习文本暗示我所做的应该只是工作。

调用类方法时省略+alloc

SNDShoutingPerson *person = [SNDShoutingPerson person];

简要:

+ (id)foo表示类方法。其形式为:

[MONObject method];

- (id)foo表示实例方法。其形式为:

MONObject * object = ...; // << instance required
[object method];

此外,在这种情况下,您可以声明+ (instancetype)person,而不是+ (SNDPerson *)person;

更改行SNDShoutingPerson *person = [[SNDShoutingPerson alloc] person];//错误

SNDShoutingPerson *person = [[SNDShoutingPerson alloc] init]; 

干杯。

如果要调用类方法:

SNDPerson person = [SNDPerson person];

person是一个类方法,但您尝试使用 alloc 返回的不完全构造实例调用它。杀死分配,只做[SNDShoutingPerson person].

顺便说一下,这与子类无关。如果您编写了 [[SNDPerson alloc] person],则会收到相同的错误。

最新更新