如何摆脱“不兼容的指针类型”?警告? [英] How to get rid of the "Incompatible pointer types" warning?

查看:231
本文介绍了如何摆脱“不兼容的指针类型”?警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的Shape类:

I have this simple Shape class:

Shape.h

#import <Foundation/Foundation.h>

@interface Shape : NSObject

-(id)initWithColor:(UIColor *)color;
+(instancetype)shapeWithColor:(UIColor *)color;

@end

和Shape.m

#import "Shape.h"

@interface Shape ()

@property (nonatomic, strong) UIColor *color;

@end


@implementation Shape

-(id)init
{
    return [self initWithColor:[UIColor whiteColor]];
}

-(id)initWithColor:(UIColor *)color
{
    self = [super init];

    if (self)
    {
        _color = color;
    }

    return self;
}

+(instancetype)shapeWithColor:(UIColor *)color
{
    return [[self alloc] initWithColor:color]; // I get the warning here
}

@end

在便利构造函数的return语句中,我得到以下警告:

In the convenience constructor's return statement, I'm getting the following warning:


不兼容的指针类型将'UIColor *'发送到类型的参数
'CIColor *'

Incompatible pointer types sending 'UIColor *' to parameter of type 'CIColor *'

我在这里做错了什么?我知道我可以写 return [[Shape alloc] initWithColor:color]; ,但是在这种情况下,如果我使用 Shape会给子类造成问题而不是 self ,对吧?

What am I doing wrong here? I know I can write return [[Shape alloc] initWithColor:color]; but in that case I will cause problems to my subclasses if I use Shape instead of self, right?

推荐答案

由于 initWithColor:也是 CIImage 的方法,定义为

The compiler is confused since initWithColor: is also a method of CIImage, defined as

- (id)initWithColor:(CIColor *)color;

您可以通过cmd单击方法名称轻松地进行验证。您将获得以下下拉列表,表明存在多个与该名称匹配的声明

You can easily verify this by cmd-clicking on the method name. You will get the following dropdown, indicating that multiple declarations matching that name exist

您可以更改名称或添加显式类型转换:

You can either change the name or add an explicit cast:

return [(Shape *)[self alloc] initWithColor:color];

强制类型转换将为编译器提供足够的信息以正确地键入检查方法参数,它将不会

The cast will provide enough information for the compiler to correctly type check the method parameters, and it won't affect the possibility for subclassing.

为了进一步阐明最后一个概念,我想强调一个事实,即不会更改运行时的对象类型。

To further clarify the last concept, I'd like to stress the fact that casting doesn't change the object type at runtime. It's just a compiler hint.

return [[Shape alloc] init];         // always  returns an object of type Shape
return (Shape *)[[self alloc] init]; // the actual type depends on what self is,
                                     // but the compiler will typecheck against
                                     // Shape

这篇关于如何摆脱“不兼容的指针类型”?警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆