2012-11-28 51 views
0

我試圖繼承UIImage類,並添加了一些自定義的init方法以及一些添加的變量。但是,當我嘗試使用新的初始化程序創建新對象時,該對象始終爲nil。新init方法如下:子類化和添加初始化方法總是返回無

- (id)initWithLat:(int)latitude andLong:(int)longitude andSize:(int)size { 
    self = [super initWithContentsOfFile:@"dot.png"]; 
    if (self) { 
     self.lat = latitude; 
     self.longi = longitude; 
     self.dotScale = size; 
    } 
    return self; 
} 

我相信我繼承正確的,這是我的頭文件:

#import <UIKit/UIKit.h> 

@interface Dot : UIImage { 
    int lat; 
    int longi; 
    int dotScale; 
} 

@property int lat; 
@property int longi; 
@property int dotScale; 

- (id)initWithLat:(int)latitude andLong:(int)longitude andSize:(int)size; 

@end 

我越來越想一個Dot對象添加到NSMutableArray當錯誤。

dots = [[NSMutableArray alloc] init]; 
[dots addObject:[[Dot alloc] initWithLat:0 andLong:0 andSize:1]]; 

我的猜測是在新的初始化器中有錯誤。我使用this作爲指導。

+0

我不認爲使用子類是正確的做法。我認爲你最好讓'Dot'成爲'UIView'的一個子類。然後'Dot'類可以將圖像添加到自身。問問自己,'Dot'真的是'UIImage'還是'Dot'是UIView',其中包含'UIImage'?這是一個經典的「是」與OOP中的「有」關係問題。 – rmaddy

+0

@maddy我所做的是創建'Dot'作爲'UIImage'的子類,默認加載'dot.png'並添加額外的參數。然後我根據這些圖像創建'UIImageViews'。在功能上它很好,我應該去另一條路線嗎? –

+0

你的'Dot'類不應該擴展'UIImage'。 「Dot」不是一個圖像,它有一個圖像。就像它有一個緯度,它有一個經度。讓'Dot'擴展'NSObject'(早些時候我說'UIView',但那是錯誤的)。然後將「UIImage」屬性與其他屬性一起添加到「Dot」中。 – rmaddy

回答

1

initWithContentsOfFile:如果無法找到文件,則返回nil。可以找到嗎?使用日誌記錄/斷點來了解您的初始者期間發生了什麼。

1

這是initWithContentsOfFile的文檔:

 
initWithContentsOfFile: 
Initializes and returns the image object with the contents of the specified file. 

- (id)initWithContentsOfFile:(NSString *)path 

Parameters 
path 
The path to the file. This path should include the filename extension that identifies the type of the image data. 

Return Value 
An initialized UIImage object, or nil if the method could not find the file or initialize the image from its contents. 

請注意,如果指定的文件不能被發現,調用將返回零。它可能是一個安全的選擇,你的'dot.png'文件沒有找到,特別是因爲你沒有指定完整的路徑。我無法想象爲什麼你想要硬編碼這個值,你可能應該爲文件名添加一個參數給初始值設定項。

相關問題