1

How to declare a C array of integers as a property on an objective-c class?

Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81

1 Answers1

6
@property (nonatomic, assign) int *array;
...
// somewhere in your code 
    int *gg = malloc(10 * sizeof(int));
    gg[1] = 1;
    gg[0] = 2;
    self.array = gg;

UPDATE:

This is heap based array now to make sure it will not be deallocated.
But don't forget to free it in dealloc free(self.array)

Basheer_CAD
  • 4,908
  • 24
  • 36
  • exactly what i was trying to achieve. the cleanest answer from all in other similar questions – Nicolas Manzini Feb 20 '14 at 12:57
  • great :)@NicolasManzini – Basheer_CAD Feb 20 '14 at 13:00
  • 1
    You can't do this. When you leave the scope where `gg` was declared your `array` property will contain pointer to a deallocated part of memory. Best case scenario you will get trash instead of values you want. In case of `int *array` array must be allocated on heap using `malloc` or `new`. – creker Feb 20 '14 at 13:06
  • 1
    the funny thing is I was reading about this heap/stack problem right now! :) i can fill it with 0s by doing gg[] = {0} ? – Nicolas Manzini Feb 20 '14 at 13:20
  • yep :) thanks to @creker for reminding :) – Basheer_CAD Feb 20 '14 at 13:21