简体   繁体   中英

Objective-C Incompatible pointer types initializing 'XYZShoutingPerson *' with an expression of type 'XYZPerson *'

I'm going through the Programming with Objective-C tutorial, and I've arrived at trying to implement the class factory method for XYZPerson

Everything looks OK until I try instantiating an object with the child class called XYZShoutingPerson. I get the following error inside main.m

Incompatible pointer types initializing 'XYZShoutingPerson *' with an expression of type '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;
}

Any help would be much appreciated.

Thank you!

The error is you are downcasting XYZPerson to XYZShoutingPerson , which need explicit cast.

What you should do is change the method return type so it matches.

+ (XYZPerson *)person; should be + (instancetype)person;

see http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-features for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM