Search code examples
objective-cmemory-managementlazy-initialization

Crash with lazy initialization


I am having problems with lazily initializing an image. In my view controller I am trying to say if the image has not been retrieved from URL, then load it.

- (UIImage *)image {
    if (!self.image) {
        self.image = [[UIImage alloc] init];

    ... get image data from url ...

        self.image = [UIImage imageWithData:urldata];
    }
    return self.image;
}

Any suggestions would be much appreciated, it creates a ton of UIImage objects and crashes the app.


Solution

  • You are making a recursive call. Never access the property in the getter or setter method of the property.

    You want:

    - (UIImage *)image {
        if (!_image) {
            _image = [[UIImage alloc] init];
    
        ... get image data from url ...
    
            _image = [UIImage imageWithData:urldata];
        }
    
        return _image;
    }
    

    The call to self.image calls this image method. Therefore if you call self.image inside the image method, it calls itself recursively.

    Actually you can call the setter from the getter and you can call the getter from the setter but I prefer be consistent to avoid any possible issues.