removeConnection results in EXC_BAD_ACCESS

2019-07-04 07:05发布

问题:

This is Apple's code

- (BOOL)removeConnection: (MIDINetworkConnection *)connection;

in

-[MIDINetworkSession removeConnection:]

yet it results in an EXC_BAD_ACCESS. This only happens in iOS 9.

Any help or workarounds?

回答1:

Yar's answer helped me, except it doesn't cover the case where a disconnection happens from the other device. Instead of storing the objects to an array in removeConnection: I have a manager object that listens to the MIDINetworkNotificationSessionDidChange notification, looks for any new connections, and adds the references to an NSMutableSet.

So, in my manager init I have:

self.connRefs = [NSMutableSet set];

[[NSNotificationCenter defaultCenter] addObserver:self 
     selector:@selector(sessionChanged:) 
     name:MIDINetworkNotificationSessionDidChange object:nil];
[self sessionChanged:nil];

... and my sessionChanged: method:

- (void)sessionChanged:(NSNotification *)n {
  // ios9 bug hack to keep ref to prevent bad_exec
  for (MIDINetworkConnection *c in [MIDINetworkSession defaultSession].connections) {
    [self.connRefs addObject:c];
  }
}

That seems like a fast way to figure out how to store a reference to each connection, no matter who initiated it. Then when the connection is removed (either by your app, or the other device), the reference is already stored, and no crash!



回答2:

It's the MIDINetworkConnection that's getting dealloced and causing the issue.

The workaround that I'm using is that I add these objects to an NSMutableArray before calling removeConnection: (mine is called connectionsThatHaveBeenClosed ;) ). Unfortunately, I have to keep this array growing until the App is closed, which is a leak.



标签: ios9 coremidi