Objective c 延迟初始化导致崩溃

Objective c 延迟初始化导致崩溃,objective-c,memory-management,lazy-initialization,Objective C,Memory Management,Lazy Initialization,我在懒洋洋地初始化映像时遇到问题。在我的视图控制器中,我试图说,如果还没有从URL中检索到图像,那么就加载它 - (UIImage *)image { if (!self.image) { self.image = [[UIImage alloc] init]; ... get image data from url ... self.image = [UIImage imageWithData:urldata]; } retu

我在懒洋洋地初始化映像时遇到问题。在我的视图控制器中,我试图说,如果还没有从URL中检索到图像,那么就加载它

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

    ... get image data from url ...

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

任何建议都将不胜感激,它会创建大量UIImage对象并导致应用程序崩溃

您正在进行递归调用。永远不要在属性的getter或setter方法中访问该属性

你想要:

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

    ... get image data from url ...

        _image = [UIImage imageWithData:urldata];
    }

    return _image;
}
调用
self.image
调用此
image
方法。因此,如果在
image
方法中调用
self.image
,它会递归地调用自身


实际上,您可以从getter调用setter,也可以从setter调用getter,但为了避免任何可能的问题,我更希望保持一致。

您正在进行递归调用。永远不要在属性的getter或setter方法中访问该属性

你想要:

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

    ... get image data from url ...

        _image = [UIImage imageWithData:urldata];
    }

    return _image;
}
调用
self.image
调用此
image
方法。因此,如果在
image
方法中调用
self.image
,它会递归地调用自身

实际上,您可以从getter调用setter,也可以从setter调用getter,但我更喜欢一致性,以避免任何可能的问题