簡體   English   中英

Objective-c:向NSMutableArray添加自定義對象

[英]Objective-c: Adding a custom object to a NSMutableArray

我通常使用Java或C ++進行編程,最近我開始使用Objective-C。 在Objective-C中尋找向量,我發現NSMutableArray似乎是最好的選擇。 我正在開發一個opengl游戲,並且試圖為我的sprite創建一個帶紋理的四邊形的NSMutableArray。 以下是相關代碼:

我定義紋理四邊形:

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

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

我在接口中創建一個數組:

@interface Sprite() {
    NSMutableArray *quads;
}

我初始化數組,並基於“寬度”和“高度”(它們是單個精靈的尺寸)以及“ self.textureInfo.width”和“ self.textureInfo.height”(它們的尺寸)來創建TexturedQuads。整個精靈表:

    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
    }
    }

問題是我不知道如何將quad“ q”添加到數組“ quads”。 簡單編寫[quads addObject:q]不起作用,因為該參數應該是一個id而不是TexturedQuad。 我已經看到了如何從int等中獲取ID的示例,但我不知道如何使用我的TexturedQuad這樣的對象來實現。

它的本質是將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];

有關更多信息,請參見此處

正如@Bersaelor指出的那樣,如果需要更好的性能,請使用純C或切換到Obj-C ++並使用向量而不是Obj-C對象。

NSMutableArray可以使用任何NSObject *,而不僅僅是結構。

如果您對使用Objective-C編程很認真,請看一些教程

此外,NSMutableArrays是為了方便起見,如果您向該Array添加/刪除很多對象,請使用普通C堆棧。 特別是對於您的用例,更底層的方法將獲得更好的性能。 請記住,Objective-C(++)只是C(++)的超集,因此您可以使用任何您已經熟悉的C(++)代碼。

當我為iOS編寫游戲策略時,每當需要執行繁重的工作時(例如,每秒被調用數百次的遞歸AI函數),我都會切換到C代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM