Created
November 16, 2018 06:35
-
-
Save cumanzor/274f5e84b239acd151b47bd8840c1d35 to your computer and use it in GitHub Desktop.
[Manually chasing memory leaks] #swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// can be made dry by adding a alloc/dealloc parameter | |
// add the DEBUGALLOC flag to Active Compilation Conditions -> Debug and use it only when necessary. | |
// note that you should be using Instruments for this, but this helps to catch issues in real time when running the app, and I gnenerally don't recommend following this approach for several reasons. | |
func LogDealloc<T>(from caller:T, filename: String = #file, line: Int = #line, funcname: String = #function){ | |
#if DEBUGALLOC | |
let file = ("\(filename)" as NSString).lastPathComponent as String | |
let objName = String(describing: type(of: caller)) | |
let objAddress = Unmanaged.passUnretained(caller as AnyObject).toOpaque() | |
var logMessage = "[DEBUG] [DEALLOC] [\(file):\(line)] \(objName) @ \(objAddress)" | |
print(logMessage) | |
#endif | |
} | |
func LogAlloc<T>(from caller:T, filename: String = #file, line: Int = #line, funcname: String = #function){ | |
#if DEBUGALLOC | |
let file = ("\(filename)" as NSString).lastPathComponent as String | |
let objName = String(describing: type(of: caller)) | |
let objAddress = Unmanaged.passUnretained(caller as AnyObject).toOpaque() | |
var logMessage = "[DEBUG] [ALLOC] [\(file):\(line)] \(objName) @ \(objAddress)" | |
print(logMessage) | |
#endif | |
} | |
//usage: | |
class MyObject { | |
init(){ | |
LogAlloc(from: self) | |
} | |
deinit{ | |
LogDealloc(from: self) | |
} | |
} | |
// output is something like this: | |
/* | |
[DEBUG] [ALLOC] [MyObject.swift:3] MyObjectOrInheritedOrProtocol @ 0x000060000154dca0 | |
[DEBUG] [DEALLOC] [MyObject.swift:7] MyObjectOrInheritedOrProtocol @ 0x000060000154dca0 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment