2010-05-12 45 views
2

這是一個令人痛心的菜鳥問題,但在這裏我正在學習一門新的語言和框架,我試圖回答「真相是什麼?」這個問題。屬於Obj-C。Objective-C的定義

我試圖通過網絡延遲加載圖像。我有一個數據類名爲事件具有的性能,包括:

@property (nonatomic, retain) UIImage image; 
@property (nonatomic, retain) UIImage thumbnail; 
在我的AppDelegate

,我取了一堆關於我的活動數據(這是一個應用程序,顯示本地藝術活動列表),並且預設置每個event.image到我的默認「no-image.png」。

然後在我看到這些東西的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; 

} 

我們從來沒有拿到NSLog的電話。測試thisEvent.image爲NULL是不是事。我也試過== nil,但那也行不通。

回答

4

延遲加載看起來就像這樣:

@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; 
} 

而且不要忘了釋放的dealloc圖像。

問候,

+1

哦,夥計。你說的是在我的Event模型類中正確地做到這一點,對吧?這比在表格視圖控制器中做得好得多,因爲我正在構建單元以保存該項目。謝謝! – 2010-05-12 14:20:44

4

如果您將image設置爲no-image.png,它不會是零(Objective-C使用nil作爲對象值,您應該使用它來代替NULL,它具有不同的目的,儘管它具有相同的值)。

2

你真的不希望爲您打造的表格單元格,從網頁加載圖像,表格滾動會是非常緩慢的。

請參閱Apple的示例LazyTableImages瞭解如何操作,this SO question也可能有所幫助。

+0

我的下一個SO問題是「爲什麼我的桌面滾動速度非常慢?」。 謝謝! – 2010-05-12 14:38:51