Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAppleEventDescriptor to NSArray

I'm trying to create an NSArray with list values from an NSAppleEventDescriptor. There was a similar question asked some years back, although the solution returns an 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") ]>

I'm not sure what descriptor function I need that will parse the values into an array.

like image 633
l'L'l Avatar asked Jan 07 '23 02:01

l'L'l


1 Answers

The returned event descriptor must be coerced to a list descriptor.
Then you can get the values with a repeat loop.

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);
like image 120
vadian Avatar answered Jan 15 '23 01:01

vadian