Created
April 16, 2016 22:51
-
-
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
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
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