Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift sometimes calls wrong method

Tags:

ios

swift

I noticed strange behaviour during working with Swift projects. I can't explain it other than Swift sometimes calls wrong method. It is very rare and even adding blank lines to the code could lead that this error is gone.

Let me explain in screenshots what I mean, next I use CoreData example of SwiftDDP project that can be found on Github, but such issues I was able to see in my own projects.

Here we at Todos.swift:74 where you can see breakpoint, I expect that next call should be getId() method of MeteorClient class because it was already instantiated:

Screenshot 1

After Step Into as you can see the ping() of the same instance is called:

Screenshot 2

The next two steps into lead to EXC_BAD_ACCESS exception:

Screenshot 3

In my project I saw this issue fairly often before I stopped using singletons, so it could be related to Swift static memory usage or I don't understand something that is not surprising as I have little experience with multithreading and memory management.

My environment is:

  • AppCode OC-145.184.11
  • Xcode Version 7.2.1 (7C1002)
  • iOS 9.2 SDK
  • Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81)

NOTE: Here I use AppCode but the same behavior I was able see in Xcode, and even more if the same issue that reproduces in Xcode could not reproduce in AppCode and vice versa.

Would be thankful if someone can explain this strange behaviour to me.

Thanks!

like image 486
rozd Avatar asked Mar 15 '16 11:03

rozd


1 Answers

This just happened on my team, using Swift 2.2. It's really incredibly strange. It's not a threading issue or an async problem, it was a very cut & dry use case. We called one instance method and another one above it got called. I deleted the method that was getting called, and then the one above THAT got called instead. Then I moved the method I was actually calling to a different location in the file, and it looked like multiple properties were getting called.

This is disturbing and worrisome, as now you feel you can't trust your code to run properly.

But we did "solve" it. We moved the method up to the code that was actually getting triggered, and after a little trial & error the right method got called. Not yet sure if this will manifest itself for other methods.

It'd be nice to be able to provide a simple project where this is happening, but it seems highly unlikely that it's possible, and I can't share a snap shot of my code base with Apple. It must be a perfect storm of something to cause a bug with Swift's run time.

like image 123
Jared Egan Avatar answered Oct 14 '22 16:10

Jared Egan