tags:

views:

251

answers:

1

Hello,

i feel like having memory leak in the next code

 while([outData length] + ptr[currentPacket].mDataByteSize < inBytesToGet && currentPacket < packetsCount)
 {
  NSLog(@" ++> %d", [aData retainCount]) ;
  NSInteger sO = ptr[currentPacket].mStartOffset ;
  NSInteger dS = ptr[currentPacket].mDataByteSize ;
  NSLog(@"     get: cP: %d tP: %d mStartOffset: %d mDataByteSize: %d", currentPacket, packetsCount, sO, dS) ;
  NSData *copyRange = [aData subdataWithRange: NSMakeRange(sO,dS)] ;
  NSLog(@" => %d", [aData retainCount]) ;
  [outData appendData:copyRange] ;
  ptr[currentPacket].mStartOffset = bytesFilled + inOffset ;
  [outPackets appendBytes: &ptr[currentPacket] length: sizeof(AudioStreamPacketDescription)] ;
  currentPacket++ ;
  bytesFilled += dS ;
 }

in each iteration aData which is NSData class increase its retainCount by 1 and it happenes after [aData subdataWithRange: NSMakeRange(sO,dS)] call... i can't understand why.

+2  A: 

A likely reason is that each “copyData” is actually referencing the data in the original. As such, the new data objects will keep a reference to the original object. This is generally an efficiency advantage, since no copy of the actual data needs to be made. (The exception would be if you planned to keep a small subrange around.)

All of the data objects will be released properly when the active NSAutoreleasePool is popped.

In general, you shouldn’t be looking at the retain count of objects anyway. Code that isn’t under your direct control can do just about whatever it wants with object references, as long as it balances its retains and releases properly. If you’re concerned about leaks, use appropriate tools such as Instruments’s Leaks instrument.

Ahruman
“as long as it balances its retains and releases properly” And it's worth pointing out that `autorelease` counts as “properly”, but does not show up right away in `retainCount`. `[[[[[[[[[foo retain] autorelease] retain] autorelease] retain] autorelease] retain] autorelease] retainCount]` is 4.
Peter Hosey
Well, I should say whatever it was before plus 4.
Peter Hosey