2013-11-03 97 views
1

我有這個簡單的形狀類:如何擺脫「不兼容的指針類型」警告?

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 

在便利構造函數的返回語句,我得到以下警告:

不兼容的指針類型將'UIColor *'發送到類型爲的參數'CIColor *'

我在做什麼錯在這裏?我知道我可以寫return [[Shape alloc] initWithColor:color];,但在那種情況下,如果我使用Shape而不是self,我會對我的子類造成問題,對吧?

+0

您的代碼看起來正確。如果你用CMD點擊'initWithColor:'它指向哪裏? –

+1

可能是bot與這個問題有關,但是你也可以在'init'方法上使用'instancetype'。這是實際的代碼?你有沒有遺漏任何東西? –

+1

@GabrielePetronella:'instancetype'實際上被推斷爲'init ...' –

回答

2

因爲initWithColor:編譯器混淆也是CIImage的方法,定義爲

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

您可以輕鬆地通過在方法名CMD單擊驗證這一點。您將獲得以下下拉列表,表明多次聲明該名稱匹配存在

enter image description here

您可以更改名稱或添加一個明確的轉換:

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

演員陣容將提供足夠的信息編譯器要正確地檢查方法參數類型,並且不會影響子類化的可能性。

爲了進一步闡明最後一個概念,我想強調一下這樣一個事實:鑄造不會在運行時更改對象類型。這只是一個編譯器提示。

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 
+0

好的,我可以更改名稱,但這不應該是這樣,對吧?另外,我還添加了兩個用於測試的初始化程序,' - (id)initWithString:(NSString *)string;'和'+(instancetype)shapeWithString:(NSString *)string;'。對於這兩個,我沒有得到編譯器警告。 – phi

+0

如果我確實使用了強制轉換,那麼我的子類將只接收「Shape」對象,這是不正確的。 – phi

+0

由於在這種情況下沒有類型不匹配,您不會收到警告。 –

相關問題