你怎么知道Cocoa剩下多少磁盘空间?

zek*_*kel 8 cocoa objective-c hard-drive

我想我想能够找到任何存储空间,而不仅仅是系统盘,但这是最重要的.

zek*_*kel 10

EDIT fileSystemAttributesAtPath:不推荐使用,使用attributesOfFileSystemForPath:error:如NSD建议的那样.当我认为它不起作用时,我犯了一个错误.

// this works
NSError *error = nil;
NSDictionary *attr = [NSFM attributesOfFileSystemForPath:@"/" error:&error];
if (!error) {
    double bytesFree = [[attr objectForKey:NSFileSystemFreeSize] doubleValue];
}
Run Code Online (Sandbox Code Playgroud)

我试过这个,attributesOfItemAtPath:错误,但返回的dict似乎没有NSFileSystemFreeNodes键.

NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSDictionary *attr = [fm attributesOfItemAtPath:@"/" error:&error];
if (!error) {
    NSLog(@"Attr: %@", attr);
}

2009-10-28 17:21:11.936 MyApp[33149:a0b] Attr: {
    NSFileCreationDate = "2009-08-28 15:37:03 -0400";
    NSFileExtensionHidden = 0;
    NSFileGroupOwnerAccountID = 80;
    NSFileGroupOwnerAccountName = admin;
    NSFileModificationDate = "2009-10-28 15:22:15 -0400";
    NSFileOwnerAccountID = 0;
    NSFileOwnerAccountName = root;
    NSFilePosixPermissions = 1021;
    NSFileReferenceCount = 40;
    NSFileSize = 1428;
    NSFileSystemFileNumber = 2;
    NSFileSystemNumber = 234881026;
    NSFileType = NSFileTypeDirectory;
}
Run Code Online (Sandbox Code Playgroud)

之后环视了一下,好像fileSystemAttributesAtPath:是返回它的方法.奇怪的.

NSFileManager *fm = [NSFileManager defaultManager];
NSDictionary *attr = [fm fileSystemAttributesAtPath:@"/"]; 
NSLog(@"Attr: %@", attr);


2009-10-28 17:24:07.993 MyApp[33283:a0b] Attr: {
    NSFileSystemFreeNodes = 5027061;
    NSFileSystemFreeSize = 20590841856;
    NSFileSystemNodes = 69697534;
    NSFileSystemNumber = 234881026;
    NSFileSystemSize = 285481107456;
}
Run Code Online (Sandbox Code Playgroud)

  • 两个批评:`error:`参数获取指向对象的指针,`NSError**`.因此,正确的空指针常量不是"nil"(它是一个指向对象的指针,可以是`<class-name>*`或`id`),它是'NULL`.更重要的是,不要抑制错误返回传递指向那里变量的指针,并且如果(并且仅当)检索属性的尝试失败,则报告错误.沉默的失败是不好的. (2认同)

Avi*_*hen 10

我用这个:

NSDictionary* fileAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:@"/"
                                                                                   error:&error];
unsigned long long freeSpace = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];
NSLog(@"free disk space: %dGB", (int)(freeSpace / 1073741824));
Run Code Online (Sandbox Code Playgroud)