Swift Leak When Initializing from @objc Protocol

Gal Orlanczyk
Feb 25, 2017 · 1 min read

Lately I’ve been working on a big leak in a framework that made objects in my app leak the moment I initialized them (Both when used from swift or Objective-C). I have found this out by one of our customers reporting that our instance doesn’t get deallocated, which was weird because they have done everything right... so probably a… LEAK!.

I started looking at Xcode 8 memory graph (which is an awesome tool you should definitely check out) and found out that for some reason one of our classes leaks objects the moment they are initialized and they doesn’t have a parent node in the graph which was very suspicious! In addition, leaks instrument showed +1 reference count for no visible reason.

After a crazy weekend of debuging with memory graph and leaks instruments I started to check parts of the code which was relevant and then I found it! initializing an object from Protocol.Type that has the @objc attribute causes a leak.

Let me exaplain with an example:

So as you can see @objc was the responsible for the issue…

I opened a ticket in Swift’s Jira: SR-3935 (Apple bug tracker: 30478887) Apple engineers marked it as Swift complier bug.

Hope I helped someone not waste time on this leak or to prevent it.

Please share with people you know working on Swift framework that needs to work also in Objective-C.

Gal Orlanczyk

Written by

Senior iOS Developer @Chegg