ios - Objective C pointers to primitive types -
i came java background , i'm trying figure out if translating following piece of java code:
public class someclass { private int[] somearray; //+....other instance variables public someclass(int arraysize) { this.somearray = new int[arraysize]; //some other initialization } }
could safely translated objective c follows:
@implementation someclass { int *_myarray; //some other private fields... } -(instancetype)initwitharraysize:(int)arraysize { if(self = [super init]) { int newarray[arraysize]; _myarray = newarray; //some other initializations } return self; } }
i'm aware of nsarray , nsnumber boxing above code sounds cleaner , more efficient, specially app need @ cases hold thousands of references someclass. @ same time i'm not sure if primitive pointers safe use arc , whether cause leaks.
i've tried following dummy test see if things work expected:
@implementation someclasstests { int *_myarray; //some other private fields... } - (void)testexample { int array[] = {4, 2, 1, 0}; _myarray = array; [self changearray:_myarray]; xctassertequal(_myarray[0], -1); xctassertequal(_myarray[1], -1); xctassertequal(_myarray[2], 1); } -(void)changearray:(int *)array { array[1] = -1; array[0] = -1; } }
the test passed, i'm still not feeling confident.
any thoughts guidance highly appreciated.
your implementation lead serious errors allocate newarray
on stack , pass pointer instance variable somearray
, once method returns stack recovered, making somearray
dangling pointer.
it's more normal in objective-c use nsarray
of nsnumber
objects this. if want create array can added after initialization, , otherwise modified, use nsmutablearray
:
@implementation someclass { nsmutablearray *_somearray; } -(instancetype)initwitharraysize:(int)arraysize { if(self = [super init]) { _somearray = [[nsmutablearray alloc] initwithcapacity:arraysize]; } return self; }
Comments
Post a Comment