Objective-C不兼容的指针类型初始化'XYZShoutingPerson *',表达式为'XYZPerson *'

时间:2013-11-11 21:00:06

标签: ios objective-c

我正在阅读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;
}

非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:8)

错误是你正在向XYZPerson投降XYZShoutingPerson,这需要明确的演员。

您应该做的是更改方法返回类型,使其匹配。

+ (XYZPerson *)person;应为+ (instancetype)person;

有关详细信息,请参阅http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-features