Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Created January 25, 2017 11:15
Show Gist options
  • Select an option

  • Save JohnSundell/378b5463a49c568e10aef2587a279b75 to your computer and use it in GitHub Desktop.

Select an option

Save JohnSundell/378b5463a49c568e10aef2587a279b75 to your computer and use it in GitHub Desktop.
Sample on how you can easily test your memory management in Swift
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)
}
}
@lightsprint09
Copy link
Copy Markdown

We are testing the memory mangagment of Object, right?

Copy link
Copy Markdown

ghost commented Apr 4, 2017

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