This is probably a total noob question, but I just can’t seem to figure this out by myself. I searched here and google, but didn’t had any luck.
I have a class with some name, for instance, ‘logme’. I implement a float *floaters in the .h file, make a property en synthesize it in the .m file. Two methods inside the .m file method1 and method2. When I perform method1 from the viewcontroller, it makes the floaters variable an array with some values. I NSLog them to check if they are and they are. After that I perform method2 which only NSLogs the same array but now the values in the array are totally different.
logme.h
@interface Logme : NSObject {
float *floaters;
}
-(void)method1;
-(void)method2;
logme.m
@implementation Logme
-(void)method1 {
floaters = (float[8]) {
1.0f, 2.0f,
3.0f, 4.0f,
6.0f, 5.0f,
7.0f, 8.0f,
};
for (int i = 0; i < 8; i++) {
NSLog(@"%f", floaters[i]);
}
}
-(void)method2 {
for (int i = 0; i < 8; i++) {
NSLog(@"%f", floaters[i]);
}
}
@end
Calling the methods from viewcontroller:
logme = [Logme alloc];
[logme method1];
[logme method2];
Outcome:
NSLog from method1:
1.000000
2.000000
3.000000
4.000000
6.000000
5.000000
7.000000
8.000000
NSLog from method2:
0.000000
-1.998885
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
- I’m sorry. I was fighting this 4 spaces system. It wouldn’t let me add the .m file code. Finally got it in here 🙂
Your are assigning a pointer to a block of memory that is in the stack, this means that when you exit from mrthod1 that memory will be deallocated.The value printed after method1 are casual, it may also happen that the memory gets not touched, but usually the stack changes at every method call, so that’s your case.
Choice 1
You are using floaters as an array, so declare it to be an array and it will have it’s own storage:
Choice 2
Let floaters be a pointer, but allocate dinamically the memory for floaters:
And don’t forget to free the memory when you don’t need it anymore.