2011-09-30 110 views
0

想要創建實例化對象的方法。實例化對象的方法

- (NSArray *) make3Of : (Class) type 
{ 
    ... 
    type * temp = [[type alloc] ... 
    ... 
} 

但我得到的Xcode警告...

實際警告: 「類方法+頁頭未找到(返回類型默認爲‘身份證’)」

有沒有更好的/正確的方式來做到這一點?

實際代碼:

- (NSArray *) getBoxesOfType: (Class <ConcreteBox>) type StartingFrom: (uint64_t) offset 
{ 
    NSMutableArray *valueArray = [[NSMutableArray alloc]initWithObjects: nil]; 

    for (uint64_t i = offset; i< boxStartFileOffset + self.size; i += [self read_U32_AtBoxOffset:i]) 
    { 
     if ([[self read_String_OfLen:4 AtBoxOffset:offset + 4] isEqual:[type typecode]]) { 

      [[type alloc]initWithFile:file withStartOffset:i]; //warning here; 

      //yes I plan to assign it to a variable 
      //(originally of "type" but that won't work as AliSoftware pointed out, will be using "id" instead. 

      ... 

     } 
    } 
} 

與實例,我試圖實例化一個連接對象。

代碼協議:

#import <Foundation/Foundation.h> 

@protocol ConcreteBox 

+ (NSString *) typecode; 

- (id) initWithFile: (NSFileHandle *) aFile withStartOffset: (uint64_t) theOffset; 

@end 
+0

的問題是沒有多少明確的。請給出實際的代碼,應該有助於理解問題。 – objectivecdeveloper

+0

添加實際代碼。 – WanderingInLimbo

+0

我沒有看到你提供的問題。你能提供實際的班級定義嗎?如果可能的話,你會得到實際的錯誤嗎? –

回答

2

不能使用一個變量(在你的情況type)...作爲一個類型,另一個變量!

在您的代碼中,typetemp都是變量,這是一個語法錯誤。

由於您不知道編譯時變量的類型,請改用動態類型id。這種類型專門用於處理在編譯時未定義類型的情況。

所以,你的代碼看起來就像這樣:

-(NSArray*)make3Of:(Class)type { 
    id obj1 = [[[type alloc] init] autorelease]; 
    id obj2 = [[[type alloc] init] autorelease]; 
    id obj3 = [[[type alloc] init] autorelease]; 
    return [NSArray arrayWithObjects:obj1, obj2, obj3, nil]; 
} 
+0

謝謝。你是正確的使用「類型」作爲變量聲明的類型 - 但我其實還沒有寫入該部分; '[alloc alloc]'已經給我帶來麻煩了。但是,這仍然沒有解決「類方法+未找到alloc(返回類型默認爲'id')」警告。 – WanderingInLimbo

+0

剛剛在Xcode中嘗試了我在上面的答案中提供的確切代碼,並且在此處沒有提示。你可以說得更詳細點嗎? – AliSoftware

+0

嗯,你是對的。看來只有在涉及協議時纔會出現警告。 '(類)'。我已經將實際的代碼粘貼到問題中了 - 應該是最初完成的,但是我是通過智能手機發布的。 – WanderingInLimbo