2

This is an agonizingly rookie question, but here I am learning a new language and framework, and I'm trying to answer the question "What is Truth?" as pertains to Obj-C.

I'm trying to lazy-load images across the network. I have a data class called Event that has properties including:

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

in my AppDelegate, I fetch up a bunch of data about my events (this is an app that shows local arts event listings), and pre-sets each event.image 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's 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 that NSLog call. Testing thisEvent.image for NULLness isn't the thing. I've tried == nil as well, but that also doesn't work.

Dan Ray
  • 21,623
  • 6
  • 63
  • 87

3 Answers3

4

If you set image to no-image.png, it won't be nil (Objective-C uses nil for object values, you should use this instead of NULL, which has a different purpose, although it has the same value).

Paul Lynch
  • 19,769
  • 4
  • 37
  • 41
4

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 do not forget to release image in dealloc.

Regards,

Quentin
  • 1,741
  • 2
  • 18
  • 29
  • 1
    Oh man. You're talking about doing that right in my Event model class, right? That's so much better than doing it in the table view controller as I'm building the cell to hold the item. Thanks! – Dan Ray May 12 '10 at 14:20
2

You really don't want to load images from the web as you build the table cells, your table scrolling will be terribly slow.

See Apple's example LazyTableImages for how to do this and this SO question may help too.

Community
  • 1
  • 1
progrmr
  • 75,956
  • 16
  • 112
  • 147