l'L*_*L'l 4 macos xcode cocoa applescript objective-c
我正在尝试NSArray从NSAppleEventDescriptor. 几年前有人问过一个类似的问题,尽管解决方案返回一个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") ]>
Run Code Online (Sandbox Code Playgroud)
我不确定我需要什么描述符函数来将值解析为数组。
返回的事件描述符必须强制转换为列表描述符。
然后您可以通过重复循环获取值。
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);
Run Code Online (Sandbox Code Playgroud)
我写了一个扩展来使这更容易。
请注意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) })
}
}
Run Code Online (Sandbox Code Playgroud)
如果有任何改进之处,请评论或编辑!
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |