How to declare a C array of integers as a property on an objective-c class?
Asked
Active
Viewed 216 times
1
-
1http://stackoverflow.com/questions/912016/declaring-properties-synthesizing-and-implementing-int-array-in-objective-c – CoolMonster Feb 20 '14 at 12:51
-
1is this you want? http://stackoverflow.com/a/912344/2629258 – sathiamoorthy Feb 20 '14 at 12:52
-
YES thanks couldn't find it – Nicolas Manzini Feb 20 '14 at 12:54
-
http://stackoverflow.com/questions/476843/create-an-array-of-integers-property-in-objective-c – Rushabh Feb 20 '14 at 13:01
-
Please see my updated answer. stack based arrays will probably get cleaned after the method call. Happy coding :) – Basheer_CAD Feb 20 '14 at 13:12
1 Answers
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 deallocfree(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
-
-
1You 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
-
1the 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
-