问题
I have this simple Shape class:
Shape.h
#import <Foundation/Foundation.h>
@interface Shape : NSObject
-(id)initWithColor:(UIColor *)color;
+(instancetype)shapeWithColor:(UIColor *)color;
@end
and 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
In the convenience constructor's return statement, I'm getting the following warning:
Incompatible pointer types sending 'UIColor *' to parameter of type 'CIColor *'
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?
回答1:
The compiler is confused since initWithColor: is also a method of CIImage, defined as
- (id)initWithColor:(CIColor *)color;
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
来源:https://stackoverflow.com/questions/19757350/how-to-get-rid-of-the-incompatible-pointer-types-warning