Max Raskin Max Raskin - 3 years ago 162
iOS Question

Adding Swift closure object to NSMutableArray and then removing it doesn't work - LEAK

I have some Swift code that interoperates with Objective C, and I noticed I'm leaking, I narrowed it down to NSMutableArray not removing my closure, here's a pure Swift snippet that reproduces the problem:

let myClosure : ((String?) -> ())! = { (fileName: String?) in

let arr = NSMutableArray()

Did anyone encounter this -- why does this happen? and how can I get it to work?

Answer Source

To re-emphasize, our codebase uses Swift that interops with ObjC, therefore, in my case its not possible to go pure Swift trivially.

I changed our API to use an NSDictionary that maps from NSUInteger handle to the closure and that integer is then used for removal of the closure from the dictionary.

The purpose of that API is to register listener callbacks and have a facility to unregister them. So that NSUInteger handle satisfies the removal bit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download