objective-c - 当 URL 为空时 dataWithContentsOfURL 返回值不为 nil

标签 objective-c iphone cocoa

我在使用 dataWithContentsOfURL 时遇到问题。 我正在循环加载来自互联网的一些图像。 问题是:如果 URL 处的图像不存在,dataWithContentsOfURL 不会按预期返回 nil。苹果引用资料称,如果无法创建 NSData,则返回 nil。 代码如下:

NSString *TermineImgFileName = nil;
NSString *TermineImgPath = nil;
NSURL *TermineImgURL = nil;
NSData *TermineImg = nil;   
for (deviceTermineHighInt; deviceTermineHighInt <= serverTermineHighInt; deviceTermineHighInt++) {
    TermineImgFileName = [NSString stringWithFormat:@"Termine%i.png", deviceTermineHighInt];
    TermineImgURL = [rootURL URLByAppendingPathComponent:TermineImgFileName];
    TermineImg = [NSData dataWithContentsOfURL:TermineImgURL];
    if (TermineImg != nil) {
        TermineImgPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:TermineImgFileName];
        [TermineImg writeToFile:TermineImgPath atomically:YES];
        updateCount += 1;
        NSLog(@"File %@ saved", TermineImgFileName);
    }
    else {
        NSLog(@"Write Error");
    }               
    TermineImg = nil;
}

你知道为什么如果 URL 处的文件不存在该方法不返回 nil 吗?

第二个问题:像我一样使用字符串、NSURLNSData 是否有意义?出于内存原因,我认为这将是最好的方法。

预先感谢您, 尼科斯

编辑:循环的变量在代码之前定义,循环工作正常。另外,变量 rootURL 是 header 中定义的常量。 URL 构建得很好并且可以正常工作。

最佳答案

我想说的问题是,如果您请求不存在的图像,服务器实际上会做什么。
如果它给你一个 404,-dataWithContentsOfURL: 应该返回 nil - 但如果没有,一个带有结果的 NSData 实例将是创建的它恰好不包含任何有用的图像数据。

关于objective-c - 当 URL 为空时 dataWithContentsOfURL 返回值不为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3188147/

相关文章:

cocoa - Cocoa 中除 MooV 之外的视频格式的操作系统类型是什么?

macos - 快速统一标题和工具栏, Storyboard没有标题可见性

Objective-C 将基类对象转换为特定类

ios - 如何在不重新加载 Objective-C 行的情况下更改行中的特定元素?

iphone - 停止使用 iPhone 进行开发

ios - 如何在 iOS 中现有的 cocoa-pod 集中添加新库

iphone - 在调用 presentOpenInMenuFromRect 之前检查它是否存在可以打开文件的应用程序

ios - Xcode 5 – iOS 7 – 在基于 Storyboard的应用程序中没有限制?

iphone - 如何声明一个 MKPolygon

cocoa - 在 Mojave 上禁用 NSScrollView 内部的活力?