0

Hi when you do lazy instantiation should you do it in the setter or getter? I have heard that you do it in the getter but what if the property is set before it is called for by a getter? Would that mean the property is still nil? Also, if you lazy instantiate in the getter and someone calls a setter function but you do not lazy instantiate in the setter what is the property value?

user2076774
  • 405
  • 1
  • 8
  • 21

1 Answers1

0

I think the getter is a better place. If the setter is called first - well, then it will set the property to whatever it is asked to do so, and nobody cares what the previous value of the property was.

- (id)foo
{
    if (_foo == nil) {
        _foo = [[Foo alloc] init];
    }
    return _foo;
}

- (void)setFoo:(id)f
{
    if (_foo != f) {
        [_foo release]; // Yay, messaging nil is safe!
        _foo = [f retain];
    }
}