Skip to content

Instantly share code, notes, and snippets.

@samritchie
Created May 19, 2016 03:00
Show Gist options
  • Save samritchie/81172456003141415f2fddcd4d3e50e9 to your computer and use it in GitHub Desktop.
Save samritchie/81172456003141415f2fddcd4d3e50e9 to your computer and use it in GitHub Desktop.
Swift Interpolated String memory leak
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Instruments shows a memory leak here
print("The number of the counting shall be \(3)")
// but not here
//print("The number of the counting shall be " + 3.description)
if let widget = store.value.currentWidget {
print(widget.widgetID)
}
return true
}
}
import Foundation
struct Doodad {
var doodadID: String
var name: String
}
struct Widget {
var widgetID: String
var doodad: Doodad
var startDate: NSDate
var endDate: NSDate?
var prop1: String?
var prop2: String?
var prop3: [String]
var prop4: [String]
var prop5: [String]
var prop6: Double
var prop7: NSDate?
}
enum NavigationState {
case Main
case Compare(Widget, Widget)
}
struct AppState {
var navigationState: NavigationState = .Main
var widgets = [Widget]()
var prop1: [String] = []
var prop2: String?
init(widget: Widget) {
widgets = [widget]
}
var currentWidget: Widget? {
return widgets.filter { $0.endDate == nil }
.sort { $0.0.startDate.compare($0.1.startDate) == .OrderedDescending }
.first
}
}
class Store<T> {
var value: T
init(_ initial: T) {
value = initial
}
}
let widget = Widget(widgetID: "sdfg", doodad: Doodad(doodadID: "8765", name: "jhg"), startDate: NSDate(), endDate: nil, prop1: nil, prop2: nil, prop3: [], prop4: [], prop5: [] , prop6: 10, prop7: nil)
let appState = AppState(widget: widget)
let store = Store<AppState>(appState)
@samritchie
Copy link
Author

Repro case for memory leak when using interpolated strings, vs no memory leak for concatenating.

It appears to be somehow related to assigning largish value types within the same scope. I’ve done my best to shrink the example down.

Note the type declarations need to be in a separate file, and optimisation set to 'fast' without -whole-module-optimization

@DivineDominion
Copy link

I suffered from NSZombies when interpolating as well. Didn't check leaks, though. Maybe related?
https://gist.github.com/DivineDominion/c069c8d3d38d7cb880b5354524acf579

http://openradar.appspot.com/26349281

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment