Question

I hope I'm not repeating an existing question but I'm having some issues retaining a data array in a Objective-C with OpenGL ES. Here's the deal:

I have this class with the following property:

@property GLfloat* data;

this class has a method that finishes with:

-(void)loadObj {
     (...)
     GLfloat glData[n];
     (...) //populate glData array
     self.data = glData;
     NSLog(@"%i", self.data[1]) 
 }

Back on my main, I create an instance of said class and proceed to call the loadObj function.

loader = [[ObjLoader alloc] init];
[loader loadObj];
data = loader.data;
NSLog(@"%i", data[1]) 

Unfortunately it's data array has lost it's information for some reason

On the first print the values are all there, the way they're intended. On the second though, almost none of the data is retained.

Is there any way I can keep this from happening? I'd like to point out that using NSMutable arrays is out of the question, because I need the data type to be GLfloat

Thanks in advance

Was it helpful?

Solution

Since a GLfloat is a C typedef that has nothing to do with Objective-C you can't retain it by using any Objective-C feature.

The problem in your example is that GLfloat glData[n] is an array with automatic allocation onto the stack. When the function in which you declared it returns to the caller, the data pointed is no longer valid.

What you should do it managing the memory by yourself:

-(void)loadObj {
     (...)
     GLfloat *glData = calloc(n, sizeof(GLfloat));
     (...) //populate glData array
     self.data = glData;
 }

In this way you are allocating the array in the heap and it won't become invalid when function exits. Mind that this memory is not managed by Objective-C so you are responsible of releasing it when needed, eg

-(void)dealloc {
  free(self.data);
  [super dealloc];
}

OTHER TIPS

The problem is that GLfloat glData[n]; is allocated on stack, i.e. it is freed as soon as you leave the method. You need to allocate memory using heap:

-(void)loadObj {
     (...)
     GLfloat *glData = (GLfloat*)malloc(n*sizeof(GLfloat)); //don't forget to free it
     (...) //populate glData array
     self.data = glData;
     NSLog(@"%i", self.data[1]) 
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top