2

I don't know how to release an Objective-C object that I have stored in an old-fashioned c-array.

(Remark: While writing this after much searching, I think I found a bug in the test-code so this seems to be a solution rather than a question. Well, I've spent a lot of time on it so I'll post it anyway...)

I'd like to convert older code to ARC, because I am spending too much time on debugging memory-management related bugs (sorry---the retain/release rules simply aren't hardwired in my spine, and it takes me literally hours to find a missing retain, because the errors pop up at unrelated moments, probably during or after memory cleanup).

So I have some existing code with c-style arrays (say a two-dimensional array of UILabel*'s), where I can happily calloc() the pointers and access them through some array[col*colstride+row*rowstride], where array is of the type UILabel **; Let's assume the UILabel*s are filled at random order, so I can't use an NSMutableArray for that.

Now in ARC, the compiler wants me to make the type of array to be UILabel *__strong*, it seems (some people write that as __strong UILabel **).

What I don't understand is how I can tell ARC to release the UILabel objects when it is time to do so (say in the dealloc() of my object that uses the c-array). In trying to understand the problem, I have a small set of objects, Memory and MemoryUnit, the former trying to store a large c-array of the latter.

-(Memory*)init {
  self = [super init];
  if (self) {
    MemoryUnit * unit = [[MemoryUnit alloc] init];
    array = (__strong id *) calloc(sizeof(MemoryUnit*), 1024);
    array[0] = unit;
  }
  return self;
}

-(void)dealloc {
  for (int i=0; i<1024; i++) array[i]=nil;
  free(array);
}

In MemoryUnit we have the objects to be stored in the c-array (so this MemoryUnit is in the place of the UILabel mentioned above). For testing I had the code

-(void)dealloc {
  NSLog(@"removed %x", (int)self);
}

in its dealloc() for debugging.

DaGhostman Dimitrov
  • 1,608
  • 20
  • 44
davidav
  • 860
  • 8
  • 12
  • 2
    You should add your solution as an answer rather than appending it to the question. It is much easier to nderstand, and it makes it possible to link to the answer. – Bryan Oakley Dec 03 '12 at 23:59

1 Answers1

0

As Bryan said, we need an answer in the stack overflow system. So I do:

Solution

Apparently, setting the array element of type MemoryUnit *__strong to nil causes the object to be released, as if this element had been declared in a @propetty and @synthesize pair of statements. This is actually suggested in C-style array of pointers to Objective-C objects under ARC I think

(I found the documentation in XCode very terse, and the ARC compiler definitions only told me what was not allowed rather than giving a hint on how to do things correctly.)

Community
  • 1
  • 1
Binarian
  • 12,296
  • 8
  • 53
  • 84