Created
January 25, 2017 11:15
-
-
Save JohnSundell/378b5463a49c568e10aef2587a279b75 to your computer and use it in GitHub Desktop.
Sample on how you can easily test your memory management in Swift
This file contains hidden or 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
class Cache<T> { | |
private lazy var objects = [String : T]() | |
func object(forKey key: String) -> T? { | |
return objects[key] | |
} | |
func addObject(_ object: T, forKey key: String) { | |
objects[key] = object | |
} | |
func removeObject(forKey key: String) { | |
objects[key] = nil | |
} | |
} | |
class CacheTests: XCTestCase { | |
func testRemovedObjectsNotRetained() { | |
class Object {} | |
// Create two variables for our object, one strong and one weak | |
var object: Object? = Object() | |
weak var weakObject = object | |
let cache = Cache<Object>() | |
// Add object to cache, and make sure the cache contains it | |
cache.addObject(object!, forKey: "key") | |
XCTAssertTrue(cache.object(forKey: "key") === object) | |
// Remove the object from the cache, since we have a local strong reference the weak reference should not be nil | |
cache.removeObject(forKey: "key") | |
XCTAssertNotNil(weakObject) | |
// Finally, nil out the strong reference, which should release the object, making the weak reference become nil | |
object = nil | |
XCTAssertNil(weakObject) | |
} | |
} |
Just curious, what is the purpose of lines 26 > 34 ? Why not skip the caching step ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We are testing the memory mangagment of Object, right?