Objective-C Certainty

This is a painfully newborn question, but here I am learning a new language and framework, and I am trying to answer the question "What is Truth?" how does Obj-C apply.

I am trying to lazily load images over the network. I have an Event data class that has properties including:

@property (nonatomic, retain) UIImage image;
@property (nonatomic, retain) UIImage thumbnail;

      

in my AppDelegate app, I am collecting a bunch of data about my events (this is the app that shows event lists in local arts) and presets each .image event to my default-no-image.png.

Then in the UITableViewController where I view these things, I do:

if (thisEvent.image == NULL) {
    NSLog(@"Going for this item image");
    UIImage *tempImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:
                  [NSURL URLWithString:
                    [NSString stringWithFormat:
                    @"http://www.mysite.com/content_elements/%@_image_1.jpg",
                              thisEvent.guid]]]];
    thisEvent.image = tempImage;

}

      

We never get this NSLog call. Testing thisEvent.image for NULLness is not that. I also tried == nil

, but that doesn't work either.

+2


a source to share


3 answers


Lazy loading will look like this:

@property (nonatomic, read-only) UIImage *image;

- (UIImage *)image {
   if (!image) {
       image = [[UIImage imageWithData:[NSData dataWithContentsOfURL:
              [NSURL URLWithString:
                [NSString stringWithFormat:
                @"http://www.mysite.com/content_elements/%@_image_1.jpg",
                          thisEvent.guid]]]] retain];
  }

  return image;
}

      



And don't forget to release the image in dealloc.

Hello,

+4


a source


If you set the image to no-image.png it will not be nil (Objective-C uses nil for object values, you should use that instead of NULL, which has a different purpose, even though it has the same value).



+4


a source


You really don't want to download images from the internet when creating table cells, the table scrolling will be very slow.

See Apple's LazyTableImages example for how to do this and this SO question might help as well.

+2


a source







All Articles