2010-07-12 52 views
0

我从苹果示例代码“LazyTableImages”中获取此代码段。在下面的代码中,它们正在初始化IconDownloader类。那么这是什么样的行为。这叫做什么样的初始化 - 概念?

*************************This Line ****************************************** 
    IconDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath]; 

************************************************************************** 

然后

if (iconDownloader == nil) 
    { 
     iconDownloader = [[IconDownloader alloc] init]; 
     iconDownloader.CustomObject = CustomObject; 
     iconDownloader.indexPathInTableView = indexPath; 
     iconDownloader.delegate = self; 
     [imageDownloadsInProgress setObject:iconDownloader forKey:indexPath]; 
     [iconDownloader startDownload]; 
     [iconDownloader release]; 
    } 

和objectForKey文档这样说:

objectForKey:

返回与给定键关联的值。

- (id)objectForKey:(id)aKey 
Parameters 

aKey 

    The key for which to return the corresponding value. 

Return Value 

The value associated with aKey, or nil if no value is associated with aKey. 
Availability 

    * Available in iPhone OS 2.0 and later. 

所以我应该相信他们是设置此行

IconDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath]; 

只是在对象设置零值。

最终问题是上述行是做什么的?

感谢

+0

目前还不清楚你在问什么,格式化会让你的问题变得更加混乱。 – 2010-07-12 10:48:22

+0

@nicolai现在还是不明确? – harshalb 2010-07-12 10:53:05

回答

3

这条线:

IconDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath]; 

没有作出新的iconDonwloader。它只是要求imageDownloadsInProgress对象(我认为它是一个NSDictionary?)尝试获取与键'indexPath'(表中的当前行)相对应的IconDownloader对象。

这段代码:

if (iconDownloader == nil) 
{ 
    iconDownloader = [[IconDownloader alloc] init]; 
    iconDownloader.CustomObject = CustomObject; 
    iconDownloader.indexPathInTableView = indexPath; 
    iconDownloader.delegate = self; 
    [imageDownloadsInProgress setObject:iconDownloader forKey:indexPath]; 
    [iconDownloader startDownload]; 
    [iconDownloader release]; 
} 

检查,以查看它是否存在。如果没有(imageDownloadsInProgress返回nil,即它无法找到该键的对象),则创建一个新的并将其添加到imageDownloadsInProgress NSDictionary中。

所有这些代码都意味着对于每个indexPath(表中的每一行),只有一个IconDownloader对象 - 它会停止您试图在上下滚动表格时多次下载该图标。

希望有所帮助。

+0

好的,谢谢。我明白 – harshalb 2010-07-12 11:24:15

+0

换句话说,他们正在使用NSDictionary作为图像缓存。这是您在多个应用程序中会看到的常见模式。 – 2010-07-12 12:32:59

+0

@Brad Larson谢谢先生 – harshalb 2010-07-12 12:59:27

1

imageDownloadsInProgress似乎是一个NSMutableDictionary。这个字典用于保存类IconDownloader的实例。这些实例存储在相应的indexPath下,因此很容易在tableView中为给定的行获取IconDownloader。

你问的这条线就是这么做的。如果IconDownloader尚未实例化并存储在字典中,它将为给定的indexPath或nil检索IconDownloader实例。