2

i have these classes :

class Song {
    var title : String = ""
    weak var album : Album?

    init() {
        self.album = Album()
    }

}

and

class Album {
    var title : String = ""
    var Songs : Array < Song > = []
    deinit {
        print(self , self.title)
    }
}

this should works fine but whenever i try to set title for album from a song instance i get nil error for album for example if execute code below :

let s = Song()
s.title = "some title for song"
s.album!.title = "some title for album"

when trying to s.album!.title = "" i get :

unexpectedly found nil while unwrapping an Optional value

deinit function called on init in Song class once

what am i doing wrong here? how should i fix this?

Mohammadalijf
  • 1,387
  • 9
  • 19
  • also i put some breakpoints before accessing album property. it doesnt give me nil but as soon as i try to access it , it become nil – Mohammadalijf Feb 26 '16 at 00:50

1 Answers1

6

Weak property becomes nil as soon as there's no other strong references to the value it holds. In your code you assign newly created Album value to it and do not store it anywhere else.

So you weak property holds the only reference to album instance and it will become nil immediately after assignment.

The fix would depend on the way you use/construct your data. If Album stores references to its songs then you should create and store album object somewhere first and then use it to initialize its songs. If Album has no references to its songs (which would probably be weird), then you can just make album variable strong.

Vladimir
  • 170,431
  • 36
  • 387
  • 313