NSAppleEventDescriptor 到 NSArray
NSAppleEventDescriptor to NSArray
我正在尝试使用 NSAppleEventDescriptor
中的列表值创建一个 NSArray
。几年前有人问 similar question,虽然解决方案 returns 是 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") ]>
我不确定我需要什么描述符函数来将值解析为数组。
必须将返回的事件描述符强制转换为列表描述符。
然后你可以通过重复循环获取值。
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);
我写了一个扩展来简化这件事。
请注意 atIndex()
/ descriptorAtIndex:
具有从一开始的索引。
extension NSAppleEventDescriptor {
func listItems() -> [NSAppleEventDescriptor]? {
guard descriptorType == typeAEList else {
return nil
}
guard numberOfItems > 0 else {
return []
}
return Array(1...numberOfItems).compactMap({ atIndex([=10=]) })
}
}
如果有任何改进,请发表评论或编辑!
我正在尝试使用 NSAppleEventDescriptor
中的列表值创建一个 NSArray
。几年前有人问 similar question,虽然解决方案 returns 是 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") ]>
我不确定我需要什么描述符函数来将值解析为数组。
必须将返回的事件描述符强制转换为列表描述符。
然后你可以通过重复循环获取值。
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);
我写了一个扩展来简化这件事。
请注意 atIndex()
/ descriptorAtIndex:
具有从一开始的索引。
extension NSAppleEventDescriptor {
func listItems() -> [NSAppleEventDescriptor]? {
guard descriptorType == typeAEList else {
return nil
}
guard numberOfItems > 0 else {
return []
}
return Array(1...numberOfItems).compactMap({ atIndex([=10=]) })
}
}
如果有任何改进,请发表评论或编辑!