这称为什么样的初始化 - 概念?

时间:2010-07-12 10:39:37

标签: iphone objective-c concept

我有来自苹果示例代码“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];

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

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

谢谢

2 个答案:

答案 0 :(得分: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对象 - 当你向上和向下滚动表时,它会停止尝试多次下载图标。

希望有所帮助。

答案 1 :(得分:1)

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

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

相关问题