Wednesday 15 May 2013

objective c - How do I release C style arrays? -



objective c - How do I release C style arrays? -

i have quantumclone class has array of cgpoints. single quantumpilot object creates quantumclone @ origin of each level. during next level quantumpilot records velocities quantumclone. @ origin of new level game loop runs code

quantumclone *c = [[self.pilot clone] copy]; c.bulletdelegate = self; c.weapon = self.pilot.weapon; [self.clones addobject:c];

but game reset , each quantumclone object in clones nsmutablearray removed.

am leaking memory assigning values cgpoint pastvelocities[4551] ?

how reset these? can't release them since not objective-c objects. need phone call c functions release memory?

@interface quantumclone : quantumpilot <nscopying> { cgpoint pastvelocities[4551]; } - (id)copywithzone:(nszone *)zone { quantumclone *c = [[[quantumclone alloc] init] autorelease]; c.weapon = self.weapon; (nsinteger = 0; < 4551; i++) { [c recordvelocity:pastvelocities[i] firing:pastfiretimings[i]]; } [c recordlatestindex:timeindex]; homecoming c; } - (void)recordvelocity:(cgpoint)vel firing:(bool)firing { cgpoint p = pastvelocities[timeindex]; p.x = vel.x; p.y = vel.y; pastvelocities[timeindex] = p; bool fired = firing; pastfiretimings[timeindex] = fired; timeindex++; } @interface quantumpilot : ccnode {} .... @property (nonatomic, retain) quantumclone *clone; - (void)copydeltas { [self.clone recordvelocity:ccp(self.vel.x, -self.vel.y) firing:self.firing]; } - (void)createclone { self.clone = [[[quantumclone alloc] init] autorelease]; self.clone.active = yes; self.clone.weapon = self.weapon; }

am leaking memory assigning values cgpoint pastvelocities[4551] ?

short answer: no.

long answer: array in code big chunk of contiguous memory cgrects live in, , has automatic storage, means allocated , deallocated automatically (when goes out of scope). in other words, when parent object destroyed, array gone along 4551 objects.

you can verify size printing result of sizeof(pastvelocities). dividing result sizeof(cgrect) tell how many objects of type can stored in it.

a deallocation must married explicit allocation. need release memory allocated dynamically (explicitly), example, using alloc function family (malloc, calloc, realloc, etc).

how reset these?

memset(pastvelocities, 0, sizeof(pastvelocities));

this reset entire array.

objective-c arrays nscopying

No comments:

Post a Comment