【问题标题】:NSAppleEventDescriptor to NSArrayNSAppleEventDescriptor 到 NSArray
【发布时间】:2016-03-03 17:26:04
【问题描述】:

我正在尝试使用来自NSAppleEventDescriptor 的列表值创建一个NSArray。几年前有人问过similar question,尽管解决方案返回了NSString

NSString *src = [NSString stringWithFormat: @"return {\"foo\", \"bar\", \"baz\"}\n"];
NSAppleScript *exe = [[NSAppleScript alloc] initWithSource:src];
NSAppleEventDescriptor *desc = [exe executeAndReturnError:nil];

NSLog(@"%@", desc);

// <NSAppleEventDescriptor: [ 'utxt'("foo"), 'utxt'("bar"), 'utxt'("baz") ]>

我不确定我需要什么描述符函数来将值解析为数组。

【问题讨论】:

    标签: objective-c xcode macos cocoa applescript


    【解决方案1】:

    必须将返回的事件描述符强制转换为列表描述符。
    然后您可以通过重复循环获取值。

    NSString *src = [NSString stringWithFormat: @"return {\"foo\", \"bar\", \"baz\"}\n"];
    NSAppleScript *exe = [[NSAppleScript alloc] initWithSource:src];
    NSAppleEventDescriptor *desc = [exe executeAndReturnError:nil];
    NSAppleEventDescriptor *listDescriptor = [desc coerceToDescriptorType:typeAEList];
    NSMutableArray *result = [[NSMutableArray alloc] init];
    for (NSInteger i = 1; i <= [listDescriptor numberOfItems]; ++i) {
        NSAppleEventDescriptor *stringDescriptor = [listDescriptor descriptorAtIndex:i];
        [result addObject: stringDescriptor.stringValue];
    }
    NSLog(@"%@", result);
    

    【讨论】:

      【解决方案2】:

      我写了一个扩展来让这更容易。

      请注意,atIndex() / descriptorAtIndex: 具有从 1 开始的索引。

      extension NSAppleEventDescriptor {
      
          func listItems() -> [NSAppleEventDescriptor]? {
              guard descriptorType == typeAEList else {
                  return nil
              }
      
              guard numberOfItems > 0 else {
                  return []
              }
      
              return Array(1...numberOfItems).compactMap({ atIndex($0) })
          }
      
      }
      

      如果有任何改进,请发表评论或编辑!

      【讨论】:

      • Objective-C 版本也不错,谢谢!
      • 确保在 AppleScript 中返回一个数组
      猜你喜欢
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多