2012-11-08 51 views
7

我做了这个函数返回的文件目录中的文件的大小,它的工作原理,但我得到警告说,我要修复,功能:警告“fileAttributesAtPath:traverseLink被弃用:在IOS第一弃用2.0

-(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警告问题(http://stackoverflow.com/questions/9019353/how-to- resolve-issues-with-fileattributesatpath-warning) –

回答

8

在大多数情况下,当您获得有关已弃用方法的报告时,请在参考文档中查找它,并告诉您要使用哪种替代方法。

fileAttributesAtPath:traverseLink: Returns a dictionary that describes the POSIX attributes of the file specified at a given. (Deprecated in iOS 2.0. Use attributesOfItemAtPath:error: instead.)

所以用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来执行类似的操作。

+0

你可以给我一个例子如何使用attributesOfItemAtPath:error: – DanM

+0

它几乎与你正在使用的相同。您可以将'nil'传递给'error:'参数以快速启动。 – rmaddy

+1

'attributesOfItemAtPath:error:'不支持符号链接。所以你的代码与问题中的'traverseLink:YES'不一样。 –

1

接受的答案忘了从问题中处理traverseLink:YES

改进的答案是同时使用attributesOfItemAtPath:error:stringByResolvingSymlinksInPath

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

这比接受的答案要好得多! –