简体   繁体   English

Objective-C Definedness

[英]Objective-C Definedness

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. 与Obj-C有关。

I'm trying to lazy-load images across the network. 我正在尝试通过网络延迟加载图像。 I have a data class called Event that has properties including: 我有一个名为Event的数据类,它具有以下属性:

@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". 在我的AppDelegate中,我获取了大量关于我的事件的数据(这是一个显示本地艺术事件列表的应用程序),并将每个event.image预先设置为我的默认“no-image.png”。

Then in the UITableViewController where I view these things, I do: 然后在我查看这些东西的UITableViewController中,我这样做:

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. 我们永远不会得到那个NSLog电话。 Testing thisEvent.image for NULLness isn't the thing. 测试thisEvent.image的NULL不是问题。 I've tried == nil as well, but that also doesn't work. 我也试过== nil ,但这也行不通。

如果你将image设置为no-image.png,它将不会是nil(Objective-C对于对象值使用nil,你应该使用它而不是NULL,它具有不同的目的,尽管它具有相同的值)。

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. 并且不要忘记在dealloc中发布图像。

Regards, 问候,

You really don't want to load images from the web as you build the table cells, your table scrolling will be terribly slow. 您真的不想在构建表格单元格时从Web加载图像,您的表格滚动速度会非常慢。

See Apple's example LazyTableImages for how to do this and this SO question may help too. 有关如何执行此操作,请参阅Apple的示例LazyTableImages此SO问题也可能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM