Skip to content

Instantly share code, notes, and snippets.

@lucianomarisi
Created April 16, 2016 22:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucianomarisi/42f06d24589f121ca88eb0a93788b833 to your computer and use it in GitHub Desktop.
Save lucianomarisi/42f06d24589f121ca88eb0a93788b833 to your computer and use it in GitHub Desktop.
Extension for ensuring one instance of a class is live at any one point
extension NSObject {
// Call this when the class being debugged is initialized
func debug_ensureOnlyOneInstanceSetup() {
let type = self.dynamicType
let currentCreatedCount = createdCount(type)
assert(currentCreatedCount == 0, "More that 1 \(self) created, potential memory leak")
setCreateCount(currentCreatedCount + 1, classType: type)
}
// Call this when the class being debugged is deinitialized
func debug_ensureOnlyOneInstanceTeardown() {
let type = self.dynamicType
setCreateCount(0, classType: type)
}
private struct AssociatedKey {
static var key = "key"
}
private func setCreateCount(count: Int, classType: AnyObject) {
let intNumber = NSNumber(integer: count)
objc_setAssociatedObject(classType, &AssociatedKey.key, intNumber, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func createdCount(classType: AnyObject) -> Int {
let intNumber = objc_getAssociatedObject(classType, &AssociatedKey.key) as? NSNumber
return intNumber?.integerValue ?? 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment