I’m not sure where to ask this and I don’t think it’s specifically about iOS but as it’s about my iOS app I thought this was as good a place as any.
I have a class with a number of properties (as they often do), one of which has a type of another class. For example a “Book” class with a “Report” property of type “BookReport”. “BookReport” is in itself a class.
Here’s the thing… occasionally accessing Book.Report returns nil, even though Book isn’t nil. I can’t see how Book.Report can be nil if Book isn’t nil and when Report is just a property of Book.
If a class (Book) has a property (Report), the type of which is another class (BookReport), is it necessary to separately initialise that property or it is enough just to initialise (or pass in to the constructor in my case) the Book class?
A quick try shows the class property (Report) to be nil. So you need to initialize it, like you would for any other object.
The easiest way to deal with that apparently is to initialize the class property in the class (Book) constructor.
Each class instance needs to be instantiated by calling New on the class.
Instantiation in the constructor (or in the Open event of a window instance or control subclass):
Self.Report = New BookReport() // you can omit Self if you want to
Alternatively in a class you define yourself, you could go for lazy instantiation:
Private Property mReport As BookReport
Computed Property Report() As BookReport
Get
If mReport Is Nil Then
mReport = New BookReport()
End
Return mReport
End
Set
// do not put any code in the setter
End
End
[quote=240207:@Jason Tait]
If a class (Book) has a property (Report), the type of which is another class (BookReport), is it necessary to separately initialise that property or it is enough just to initialise (or pass in to the constructor in my case) the Book class?[/quote]
Yes
EVERY reference type needs to, at some point, set the reference to a valid instance other wise it will be nil
This could be from creating one via NEW
Or from accessing a method that returns a valid instance that you retain