Skip to content

Instantly share code, notes, and snippets.

@cumanzor
Created November 16, 2018 06:35
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 cumanzor/274f5e84b239acd151b47bd8840c1d35 to your computer and use it in GitHub Desktop.
Save cumanzor/274f5e84b239acd151b47bd8840c1d35 to your computer and use it in GitHub Desktop.
[Manually chasing memory leaks] #swift
// 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