Question

I'm using Multipeer-Connectivity.

When the session ends, the app comes to the main menu and all network stuff is released then deallocated.

But my dealloc method is called in main thread and the MCSession object takes a very long time to release itself, I don't know why, and consequently the main menu screen freezes.

If somebody know why MCSession could be so long, I'm interested. But if it comes from the MCSession itself, is it a good solution to do this?

-(void) dealloc
{
    //... other release

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [_session release];
        _session = nil;
    });

    [super dealloc];
}

EDIT: nope, it's definitely not a good solution, because it makes my app crashing. Anyway, other ideas?

Was it helpful?

Solution

When you call [_session release] since _session is an Ivar, the compiler will replace this line by [self->_session release] and the block will retain self instead of the iVar _session. Here you have 2 problems:

  1. Trying to retain an object(self) which are deallocating.

  2. When the queue will be executed, it'll call self which is already deallocated.

The following solution create a local variable which point to the same address as the iVar and release it inside the block, the block will not capture self.

-(void) dealloc
{
    //... other release
    MCSession* localSession = _session;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [localSession release];
    });

    [super dealloc];
}

OTHER TIPS

bsarr007's solution will work for non-ARC projects. If you are using ARC, you can try this:

__block MCSession *localSession = _session;
_session = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    oldSession = nil;
});

It works for me. What I am doing here is increasing reference count of MCSession object by creating new local variable that points to that object, so it won't be deallocated immediately when setting _session = nil. After that I am running asynchronously the code that decreasing reference counter of my MCSession object using background queue.

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