Skip to content

Instantly share code, notes, and snippets.

@alextrob alextrob/AppDelegate.swift
Last active Feb 16, 2017

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Feb 16, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.