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

标签 ios objective-c

我正在浏览 Programming with Objective-C教程,我已经开始尝试为 XYZPerson 实现类工厂方法

在我尝试用名为 XYZShoutingPerson 的子类实例化一个对象之前,一切看起来都很好。我在 main.m

中收到以下错误

不兼容的指针类型用类型为“XYZPerson *”的表达式初始化“XYZShoutingPerson *”

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

主.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;
}

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

错误是您正在将 XYZPerson 向下转换为 XYZShoutingPerson,这需要显式转换。

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

+ (XYZPerson *)person; 应该是 + (instancetype)person;

参见 http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-features了解更多详情

关于ios - Objective-C 不兼容的指针类型用类型为 'XYZShoutingPerson *' 的表达式初始化 'XYZPerson *',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915844/

相关文章:

ios - UITableView 单元的单元测试。访问单元的 Nib

php - 从 is_mobile 中排除 iPad 和平板电脑

iOS 自定义 UIButton 未出现在 View 中

iphone - iPhone 上的 FTP 下载速度非常慢

objective-c - ARC 占用大量内存

iphone - 为什么应用程序从词典获取数据时崩溃?

ios - 快速迭代数组时出错

iOS + 网络服务 + 内联网

ios - SQLStatement 被拒绝

ios - 如何让 UICollectionView 单元格可以在其 setSelected : method? 中被多选