【问题标题】:Objective-c: Adding a custom object to a NSMutableArrayObjective-c:将自定义对象添加到 NSMutableArray
【发布时间】:2012-07-04 00:53:10
【问题描述】:

我通常使用 java 或 c++ 编程,最近我开始使用 Objective-c。在 Objective-c 中寻找向量时,我发现 NSMutableArray 似乎是最好的选择。我正在开发一个 opengl 游戏,我正在尝试为我的精灵创建一个纹理四边形的 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”,它们是整个精灵表的尺寸:

    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”中。简单的写 [quads addObject:q] 不起作用,因为参数应该是 id 而不是 TexturedQuad。我已经看到了如何从 int 等创建 id 的示例,但我不知道如何使用我的 TexturedQuad 之类的对象来做到这一点。

【问题讨论】:

    标签: objective-c struct nsmutablearray


    【解决方案1】:

    它的本质是将 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

    正如@Bersaelor 所指出的,如果您需要更好的性能,请使用纯 C 或切换到 Obj-C++ 并使用向量而不是 Obj-C 对象。

    【讨论】:

    • 试过了,现在似乎一切正常。谢谢!
    【解决方案2】:

    一个 NSMutableArray 可以接受任何 NSObject* 而不仅仅是结构体。

    如果您对使用 Objective-C 编程很认真,请查看一些 tutorials

    此外,NSMutableArrays 是为了方便起见,如果您向该数组添加/删除大量对象,请使用普通的 C 堆栈。 特别是对于您的用例,更底层的方法将获得更好的性能。 请记住,Objective-C(++) 只是 C(++) 的超集,因此您可以使用您已经熟悉的任何 C(++) 代码。

    当我为 iOS 编写游戏策略时,每当我不得不做繁重的工作(即每秒被调用数百次的递归 AI 函数)时,我都会切换到 C 代码。

    【讨论】:

    • 谢谢!教程看起来不错。我看过其他一些教程,但是当您已经了解其他编程语言时,其中很多都是缓慢而无聊的。这些教程看起来不错且直接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2023-03-12
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多