虽然我对C#并不陌生,但是我在Objective C和iOS开发方面是一个全新的人。所以我正在学习语言。我不明白的是下面的代码为什么会引发编译器错误(是的,这是来自使用Objective 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;
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句