简体   繁体   中英

On which kind of memory a C struct is allocated when initialized as a class variable in Objective-C

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)?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM