Skip to content

Instantly share code, notes, and snippets.

@externvoid
Last active December 15, 2015 13:05
Show Gist options
  • Save externvoid/e5e18af33e6d6a46a769 to your computer and use it in GitHub Desktop.
Save externvoid/e5e18af33e6d6a46a769 to your computer and use it in GitHub Desktop.
class Person {
var friend: Person? = nil
}
let a = Person() // aオブジェクトの参照カウントは1
let b = Person()
a.friend = b
b.friend = a // aオブジェクトの参照カウントは2
a = nil
b = nil
// ここでメモリリークが発生。friendプロパティーはオブジェクトを参照しているため、オブジェクトの参照カウントは0になら無い
// a.friend = nilとしようとしても、nil not have friend propertyとなる。
// そこで
class Person {
weak var friend: Person? = nil
}
let a = Person() // aオブジェクトの参照カウントは1
let b = Person()
a.friend = b
b.friend = a // aオブジェクトの参照カウントは1のママ
a = nil // bオブジェクトの参照カウントは0になり、リリースタイミングでheapから消える
b = nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment