1

在 CSV 文件 ( ) 的终端中运行 BSD 的元数据工具$ mdls foo.csv将产生如下输出:

kMDItemContentCreationDate     = 2014-08-27 15:28:16 +0000
kMDItemContentModificationDate = 2014-08-27 15:28:16 +0000
kMDItemContentType             = "public.comma-separated-values-text"
kMDItemContentTypeTree         = (
    "public.comma-separated-values-text",
    "public.delimited-values-text",
    "public.text",
    "public.data",
    "public.item",
    "public.content"
)
kMDItemDateAdded               = 2014-08-27 15:28:16 +0000
kMDItemDisplayName             = "foo.csv"
kMDItemFSContentChangeDate     = 2014-08-27 15:28:16 +0000
kMDItemFSCreationDate          = 2014-08-27 15:28:16 +0000
kMDItemFSCreatorCode           = ""
kMDItemFSFinderFlags           = 0
kMDItemFSHasCustomIcon         = (null)
kMDItemFSInvisible             = 0
kMDItemFSIsExtensionHidden     = 0
kMDItemFSIsStationery          = (null)
kMDItemFSLabel                 = 0
kMDItemFSName                  = "foo.csv"
kMDItemFSNodeCount             = (null)
kMDItemFSOwnerGroupID          = 20
kMDItemFSOwnerUserID           = 501
kMDItemFSSize                  = 962
kMDItemFSTypeCode              = ""
kMDItemKind                    = "comma-separated values"
kMDItemLogicalSize             = 962
kMDItemPhysicalSize            = 4096

我想在代码中捕获此输出并将其转换为 NSDictionary。

...

//
// run mdls on file
//

NSURL *url = @"path/to/file/foo.csv";

NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;

NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/mdls";
task.arguments = @[url];
task.standardOutput = pipe;

[task launch];

NSData *data = [file readDataToEndOfFile];
NSString *content = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

//
// populate dictionary
//
NSDictionary *dictionary = [NSDictionary alloc] init];

// pseudo-code
NSArray *rows = split string on \n to create array of rows;

for each row {

  if (row doesn't end with a '(' or start with a ')') { 
    split rows on \= to create key and value;
    add key and value to dictionary;
  }

  else if (row starts with a '(') {
    add key to dictionary; 
    create NSArray; 
    set marker on;
  }

  else if (row ends with a ')') {
    add value to dictionary;
    set marker off;
  }

  if (marker) {
    add value to array;
  }
}

//

有没有更优雅的方法?

4

1 回答 1

2

有没有更优雅的方法?

男孩,有没有!;)

mdls当该命令基于您可以自己使用的 API 构建时,您为什么要尝试解析该命令的输出?

MDItemRef item = MDItemCreateWithURL(NULL, (__bridge CFURLRef)url);
CFArrayRef names = MDItemCopyAttributeNames(item);
NSDictionary* dictionary = CFBridgingRelease(MDItemCopyAttributes(item, names));
CFRelease(names);
CFRelease(item);

(而且,仅仅因为您询问解析 的输出mdls,我会指出它有一个-plist选项。如果您使用它并指定-为文件,您可以从其标准输出中读取一个 plist 并使用解析它NSPropertyListSerialization。)

于 2014-11-25T03:13:57.867 回答