我正在阅读Programming with Objective-C教程,我已经到了尝试为XYZPerson实现类工厂方法
在我尝试使用名为XYZShoutingPerson的子类实例化对象之前,一切都看起来不错。我在main.m
不兼容的指针类型初始化'XYZShoutingPerson *',表达式为'XYZPerson *'
XYZPerson.h
#import <Foundation/Foundation.h>
@interface XYZPerson : NSObject
@property NSString *firstName;
@property NSString *lastName;
@property NSDate *dateOfBirth;
+ (XYZPerson *)person;
- (void)sayHello;
- (void)saySomething:(NSString *)greeting;
@end
XYZPerson.m
#import "XYZPerson.h"
@implementation XYZPerson
+ (id)person
{
return [[self alloc] init];
}
- (void)sayHello
{
[self saySomething:@"Hello, World!"];
}
- (void)saySomething:(NSString *)greeting
{
NSLog(@"%@", greeting);
}
@end
XYZShoutingPerson.h
#import "XYZPerson.h"
@interface XYZShoutingPerson : XYZPerson
@end
XYZShoutingPerson.m
#import "XYZShoutingPerson.h"
@implementation XYZShoutingPerson
- (void)saySomething:(NSString *)greeting
{
NSString *uppercaseGreeting = [greeting uppercaseString];
[super saySomething:uppercaseGreeting];
}
@end
的main.m
#import <Foundation/Foundation.h>
#import "XYZPerson.h"
#import "XYZShoutingPerson.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
XYZPerson *newPerson = [XYZPerson person];
[newPerson sayHello];
XYZShoutingPerson *shoutingPerson = [XYZShoutingPerson person];
[shoutingPerson sayHello];
}
return 0;
}
非常感谢任何帮助。
谢谢!
答案 0 :(得分:8)
错误是你正在向XYZPerson
投降XYZShoutingPerson
,这需要明确的演员。
您应该做的是更改方法返回类型,使其匹配。
+ (XYZPerson *)person;
应为+ (instancetype)person;
有关详细信息,请参阅http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-features