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 文档这样说:

对象键:

返回与给定键关联的值。

- (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];

仅用于在对象中设置 nil 值。

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

谢谢

4

2 回答 2

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 对象 - 当您上下滚动表格时,它会阻止您多次尝试下载图标。

希望有帮助。

于 2010-07-12T11:19:27.953 回答
1

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

你问的那条线就是这样做的。如果 IconDownloader 之前没有被实例化并存储在字典中,它会为给定的 indexPath 或 nil 检索 IconDownloader 实例。

于 2010-07-12T11:20:54.477 回答