Skip to content

Instantly share code, notes, and snippets.

@alextrob
Last active February 16, 2017 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alextrob/3f4ddf623c24fa1773323a0281569d9f to your computer and use it in GitHub Desktop.
Save alextrob/3f4ddf623c24fa1773323a0281569d9f to your computer and use it in GitHub Desktop.
Swift: Memory leak when storing enum in class
//
// AppDelegate.swift
// LeakCheck
//
// Created by Alex Robinson on 15/2/17.
// Copyright © 2017 Alex Robinson. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var section = Section()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true }
func applicationWillResignActive(_ application: UIApplication) { }
func applicationDidEnterBackground(_ application: UIApplication) { }
func applicationWillEnterForeground(_ application: UIApplication) { }
func applicationDidBecomeActive(_ application: UIApplication) { }
func applicationWillTerminate(_ application: UIApplication) { }
}
struct Item { }
enum DownloadStatus {
case unknown, success, failure
}
class ItemList {
var downloadStatus: DownloadStatus = .unknown // This is the problematic property. Comment it out, or change it to a Bool and there is no leak.
var contents: [Item]
init(contents: [Item]) {
self.contents = contents
}
}
class Section {
var lists: [ItemList] = []
init() {
populateData()
}
func populateData() {
/*
A `_ContiguousArrayStorage<Item>` is leaked for each `ItemList`.
Leak Checks Instrument output:
Leaked Object # Address Size Responsible Library Responsible Frame
_ContiguousArrayStorage<Item> 1 0x17004d800 48 Bytes libswiftCore.dylib swift_slowAlloc
_ContiguousArrayStorage<Item> 1 0x17004dcb0 48 Bytes libswiftCore.dylib swift_slowAlloc
_ContiguousArrayStorage<Item> 1 0x17004db60 48 Bytes libswiftCore.dylib swift_slowAlloc
_ContiguousArrayStorage<Item> 1 0x17004dce0 48 Bytes libswiftCore.dylib swift_slowAlloc
_ContiguousArrayStorage<Item> 1 0x17004de30 48 Bytes libswiftCore.dylib swift_slowAlloc
*/
self.lists = [
ItemList(contents: [Item()]),
ItemList(contents: [Item(), Item()]),
ItemList(contents: [Item(), Item(), Item()]),
ItemList(contents: [Item(), Item(), Item(), Item()]),
ItemList(contents: [Item(), Item(), Item(), Item(), Item()]),
]
}
}
@alextrob
Copy link
Author

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