1

What would be a good way to pick cache file names for images downloaded from internet for caching purpose to ensure that no matter what the URL is we got valid file name?

We often pick images from the net. It's often useful to store those images in temporary cache so we don't keep downloading the same image again and again.

So I suppose, I would need a cacheFileName. It should be a function of the URL. However, it must not contain special characters like :, /, &

In other words, it has to be a valid file name.

What would be the way to do so?

I can make some my self. Perhaps I can use URLEncode which seems to do just fine. However, I wonder, if there are consideration I missed.

This is the current Code I use:

- (NSString *) URLEncodedString {
    NSMutableString * output = [NSMutableString string];
    const char * source = [self UTF8String];
    int sourceLen = strlen(source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = (const unsigned char)source[i];
        if (false && thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

It's taken from some great answer in stackOverflow which I have forgotten.

I wonder if the result of this function will always get a valid file name. Does anyone has better file name generator?

4

1 回答 1

1

如果您进行了适当的网络连接,则可以自动NSURLCache处理图像缓存

但是,我感觉您对缓存并不真正感兴趣,而是对(或多或少永久)存储图像感兴趣。

在这种情况下,为您的应用构建合适的模型。

因为您没有告诉我们您要存储的图像的用途,所以我没有比这更有帮助的了:

如果您使用的是 iOS 5+/OS X 10.7+,您可以使用NSAttributeDescription'allowExternalBinaryDataStorage 设置来NSSQLiteStoreType代表您透明地为图像数据命名、创建、检索、更新和删除支持文件。

如果您必须支持较旧的操作系统版本,您仍然可以通过瞬态属性使用外部存储。但是,您的实体描述必须具有数据文件名称的属性。在这种情况下,图像数据的 SHA-1(可通过 CommonCrypto 框架获得)将提供一个好的文件名。


在旁边

如果您在 Objective-C 的答案中找到了该代码,请对其投反对票,并删除上面的代码:

-[NSString stringByAddingPercentEscapesUsingEncoding:],并CFURLCreateStringByAddingPercentEscapes完全按照他们(或他们的文档)所说的去做。

于 2012-10-17T06:38:26.940 回答