2012-07-03 52 views
0

我通常使用java或C++編程,最近我使用objective-c開始編程。在objective-c中尋找向量,我發現NSMutableArray似乎是最好的選擇。我正在開發一款opengl遊戲,我正在嘗試爲我的精靈創建一個紋理四邊形的NSMutableArray。下面是相關的代碼:Objective-c:將自定義對象添加到NSMutableArray

我定義紋理四邊形:

typedef struct { 
    CGPoint geometryVertex; 
    CGPoint textureVertex; 
} TexturedVertex; 

typedef struct { 
    TexturedVertex bl; 
    TexturedVertex br;  
    TexturedVertex tl; 
    TexturedVertex tr;  
} TexturedQuad; 

創建在界面的數組:

@interface Sprite() { 
    NSMutableArray *quads; 
} 

我啓動陣列和我創建基於texturedQuads「寬度「和」高度「,它們是單個精靈的尺寸,以及」self.textureInfo.width「和」self.textureInfo.height「,它們是整個精靈表的尺寸:

quads = [NSMutableArray arrayWithCapacity:1]; 
    for(int x = 0; x < self.textureInfo.width/width; x++) { 
    for(int y = 0; y < self.textureInfo.height/height; y++) { 
     TexturedQuad q; 
     q.bl.geometryVertex = CGPointMake(0, 0); 
     q.br.geometryVertex = CGPointMake(width, 0); 
     q.tl.geometryVertex = CGPointMake(0, height); 
     q.tr.geometryVertex = CGPointMake(width, height); 

     int x0 = (x*width)/self.textureInfo.width; 
     int x1 = (x*width + width)/self.textureInfo.width; 
     int y0 = (y*height)/self.textureInfo.height; 
     int y1 = (y*height + height)/self.textureInfo.height; 

     q.bl.textureVertex = CGPointMake(x0, y0); 
     q.br.textureVertex = CGPointMake(x1, y0); 
     q.tl.textureVertex = CGPointMake(x0, y1); 
     q.tr.textureVertex = CGPointMake(x1, y1); 

     //add q to quads 
    } 
    } 

問題是我不知道如何將四方「q」添加到數組「四邊形」。簡單的寫法[quads addObject:q]不起作用,因爲參數應該是一個id而不是TexturedQuad。我見過如何從int等創建一個id的例子,但我不知道如何使用像我的TexturedQuad這樣的對象。

回答

2

一個NSMutableArray接受任何NSObject *,但不僅僅是結構。

如果您認真對待Objective-C的編程,請看一下tutorials

此外,NSMutableArrays是爲了方便起見,如果您添加/刪除大量的對象到該數組,使用普通的C堆棧。 尤其對於您的用例,更低級的方法會獲得更好的性能。請記住,Objective-C(++)只是C(++)的一個超集,因此您可以使用您熟悉的任何C(++)代碼。

當我爲iOS編寫我的遊戲tactica時,無論何時我不得不進行繁重的提升(即遞歸AI函數每秒被調用數百次),我都切換到了C代碼。

+0

謝謝!教程看起來不錯。我已經看過其他一些教程,但是當你已經瞭解其他編程語言時,其中很多教程都很慢,很無聊。這些教程看起來不錯並且直截了當。 –

5

它的本質是你將你的C結構包裝在一個Obj-C類中。使用的Obj-C類是NSValue

// assume ImaginaryNumber defined: 
typedef struct { 
    float real; 
    float imaginary; 
} ImaginaryNumber; 

ImaginaryNumber miNumber; 
miNumber.real = 1.1; 
miNumber.imaginary = 1.41; 

// encode using the type name 
NSValue *miValue = [NSValue value: &miNumber withObjCType:@encode(ImaginaryNumber)]; 

ImaginaryNumber miNumber2; 
[miValue getValue:&miNumber2]; 

查看here瞭解更多信息。

As @Bersaelor指出,如果您需要更好的性能,請使用純C或切換到Obj-C++並使用矢量代替Obj-C對象。

+0

嘗試了這一切,現在似乎一切正常。謝謝! –

相關問題