views:

325

answers:

3

Consider the following:

typedef struct
{
  float m00, m01, m02, m03;
  float m10, m11, m12, m13;
  float m20, m21, m22, m23;
  float m30, m31, m32, m33;
} Matrix;

@interface TestClass : NSObject
{
  Matrix matrix;
}

- (TestClass *) init;
@end


@implementation TestClass
- (TestClass *) init
{
  self = [super init];
  matrix = (Matrix) {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
  return self;
}
@end

How to ensure that the 64 bytes allocated with the struct are properly released whenever the "matrix" variable is not relevant anymore (or whenever the whole object is released)?

+5  A: 

In this case matrix should be embedded in the struct that is generated by the ObjectiveC compiler for instances of TestClass. Its lifetime is bound to the instance of TestClass which it is part of, just like an int or float member would be.

You can easily test this, if you inspect the pointers.

TestClass* testAddress = [[TestClass alloc] init];
Matrix* matrixAddress = &(testAddress->matrix);

int rawTest = (int) testAddress;
int rawMatrix = (int) matrixAddress;
int memberOffset = rawMatrix - rawTest;

printf("%i", memberOffset);

I have no compiler here, but I guess it will just mumble some warnings about evil typecasts and generate the code anyways. The output should be constant, something like 4 or 8, depending on your target architecture.

Stefan Tannenbaum
Bingo! (a struct inside a struct does make sense for me now...)
Ariel Malka
+3  A: 

In this case, there's absolutely nothing that you have to do to the structure to get free its memory when the object containing it is deallocated. The memory for the structure is inline in the object.

clarkcox3
+1  A: 

As an aside, the Core Animation struct CATransform3D has the same internal structure as your matrix:

struct CATransform3D
   {
   CGFloat m11, m12, m13, m14;
   CGFloat m21, m22, m23, m24;
   CGFloat m31, m32, m33, m34;
   CGFloat m41, m42, m43, m44;
};

Instead of defining a custom type, you may wish to use this one that Apple provides. Apple also provides some very handy functions for manipulating these matrices.

Brad Larson
Good to know but the matrix functions I'm planning to use are more adapted in the context of OpenGL ES on the IPhone...
Ariel Malka
Core Animation is backed by OpenGL, so I believe the matrix manipulation functions like CATransform3DRotate map directly to the equivalent OpenGL model view matrix operations.
Brad Larson
OpenGL ES means no "direct mode" vertex manipulation, so you end-up being the one transforming the vertice (OpenGL matrix operations can't help here) and in such case: you need optimized matrix maths functions -- e.g. rotateX(angle) -- that usually are not available in standard libraries...
Ariel Malka