警告:“fileAttributesAtPath:traverseLink已过时:在iOS 2.0中首次过时。”

8

我编写了一个函数,用于返回文档目录中文件的大小。它能够正常运行,但是我希望能够修复一个警告。以下为该函数:

-(unsigned long long int)getFileSize:(NSString*)path
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,        NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getFilePath = [documentsDirectory stringByAppendingPathComponent:path];

NSDictionary *fileDictionary = [[NSFileManager defaultManager] fileAttributesAtPath:getFilePath traverseLink:YES]; //*Warning
unsigned long long int fileSize = 0;
fileSize = [fileDictionary fileSize];

return fileSize;
}

警告是“fileAttributesAtPath:traverseLink:在ios 2.0中首次过时”。这是什么意思,我该如何修复它?


1
可能是重复的问题:如何解决fileAttributesAtPath警告的问题? - Cœur
2个回答

9
在大多数情况下,当您收到有关弃用方法的报告时,您可以在参考文档中查找,它会告诉您要使用什么替代方法。

fileAttributesAtPath:traverseLink: 返回描述给定路径指定的文件的POSIX属性的字典。(iOS 2.0中已废弃。请改用attributesOfItemAtPath:error:。)

因此,请改用attributesOfItemAtPath:error:
以下是简单的方法:
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:getFilePath error:nil];

更完整的方法是:
NSError *error = nil;
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:getFilePath error:&error];
if (fileDictionary) {
    // make use of attributes
} else {
    // handle error found in 'error'
}

编辑:如果您不知道已弃用的含义,它意味着该方法或类现在已过时。您应该使用更新的API来执行类似的操作。


请问能否给我一个使用attributesOfItemAtPath:error:的例子? - DanM
它与您正在使用的几乎完全相同。您可以将 nil 传递给 error: 参数,以快速开始。 - rmaddy
1
attributesOfItemAtPath:error: 不支持符号链接。因此,你的代码与问题中的 traverseLink:YES 没有相同的行为。 - Cœur
1
@rmaddy并不完全正确,attributesOfItemAtPath:error:的文档并没有提供明确的解决方案。请查看我的答案以了解如何解决这个问题。 - Cœur
@rmaddy,你是对的!我找不到它是因为我碰巧读了attributesOfFileSystemForPath:error:的文档,而不是attributesOfItemAtPath:error: - Cœur
显示剩余2条评论

2

原回答忘记处理问题中的traverseLink:YES

改进的回答使用attributesOfItemAtPath:error:stringByResolvingSymlinksInPath两个方法:

NSString *fullPath = [getFilePath stringByResolvingSymlinksInPath];
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:nil];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接