开发者

Class specific arrays

I'm making a simple opengl-engine and I need to be able to store series of integers for every class, containing animation frames.

Example: I create the class Dog. The Dog has 3 animations consisting of a number of frame indexes, representing the frame's position in the texture atlas. In the class file I want to define these animations like this:

const int animations[3] = {
    {1,2,3}, //walk
    {4,5,6}, //jump
    {1,7,8,9,10,11} //take a wiz
}

@implementation...

This is ofc not proper Obj-C, but is there a way to do something sim开发者_StackOverflow社区ilar? Every instance of Dog will have the same animations so I dont want to waste memory by storing the animations in instance variables. If possible, I'd like to avoid using NSArray's.

Is there a way to store 2 dimensional, variable length arrays of ints like this at class level?


You can certainly declare a static 2-dimensional array of int's. For example:

static int animations[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

Because this is declared "static", animations will not be visible outside the scope of the source file that declares it, and there'll be only one copy of the array.

The trick is, C arrays have to be rectangular, and your example shows rows of different width.

To do that, you could use an array of pointers:

static int walk[] = {1,2,3};
static int run[] = {4,5,6};
static int wiz[] = {1,2,3,4,5,6};
static int *animations[3] = {walk,run,wiz};

(In that case, of course, you'd need some other means to know when you'd come to the end of a row, since they're not all the same length. For example, maybe the end of a row is marked with a '0' or '-1' value.)


It's possible to store two-dimensional arrays at any level you want, but 2D arrays where the rows have variable length are not generally all that useful except in special circumstances.

Anyway, the traditional way to pretend like Objective-C has class variables is just to make a static variable in the class's implementation file and create class methods to access it.


Declare a static global variable in the .m file, just as you would do in C. If you need to access it outside of the class, create a class method (e.g. + (const int *)animations) to use as an accessor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜