Theocacao
Leopard
Design Element
Comment on "Lazy Loading of KVO Observed Properties"
by Blain — Jun 18

MyClass* myObject = [[MyClass alloc] init]; NSImage* currentImage = [myObject myImage]; [myObject setMyImage:nil]; currentImage = [myObject myImage];

Wouldn't this mean that using nil as an indicator would be not good? I mean, if you're trying to release myObject's image and indicate that there is no image, setting to nil instead serves as a reset/reload, which probably isn't the intent. How about this, instead?

@interface MyClass: NSObject {
    NSImage * _myImage;
    BOOL loadedMyImage;
}
@end
@implementation MyClass

- (NSImage *) myImage; {
    if (!loadedMyImage) {
        loadedMyImage = YES;
        [self setMyImage:[self loadImage]];
    }
    return _myImage;
}
- (void) setMyImage: (NSImage *) newMyImage; {
    loadedMyImage = YES;
    if (newMyImage == _myImage) {return;}
    [_myImage release];
    _myImage = [newMyImage retain];
}
@end

That way, if, for some reason, instead of loading the image, if the nib specifies an image, and it's later nilled out, the loadImage isn't inappropriately called if someone checks or is otherwise bound.

Also: is there any command that can set a bit/bool and return its previous value, atomically? That way, you don't need locks on loadedMyImage, and it'd be threadsafe.

Back to "Lazy Loading of KVO Observed Properties"
Design Element

Copyright © Scott Stevenson 2004-2015