Question

I am using NSFileHandle to read data from a socket. This is how I am creating the filehandle:

filehandle = [[NSFileHandle alloc] initWithFileDescriptor:sock closeOnDealloc:YES];

I am doing this:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readData:)    name:nil object:filehandle];
[filehandle readInBackgroundAndNotify];

I notice that, readInBackgroundAndNotify is increasing the retainCount of the fileHandle by 1. Hence when I release this filehandle once I am done reading data, the memory is not released. And hence it is trying to read some invalid data and the app is crashing. Please note that this issue is occurring in ios 4.3 but not in ios 5. I am removing observer before releasing the filehandle. Is there anything else I should be doing before releasing the file handle object?

Was it helpful?

Solution

I notice that, readInBackgroundAndNotify is increasing the retainCount of the fileHandle by 1.

As it likely should as a part of an implementation detail... you are asking the filehandle to effectively be scheduled on the background such that if data were to arrive, it will notify.

Note that retainCount is useless; it might have increased by 5 or 42 in this situation. It is irrelevant. The bottom line is that you are asking it to do something in the background and until the "stop doing stuff in background" state is reached, the object might likely still be live.

Hence when i release this filehandle once I am done reading data, the memory is not released.

Have you told the file handle to stop reading in background? Perhaps by closeing it? If not, it might likely continue.

The difference between iOS 4 and 5 is that there may be logic where the file handle notes that there are no more observers and, thus, stops reading automatically. Again, an implementation detail that you should not count on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top