Search code examples
objective-cmacoscocoaapplescript

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.


Solution

  • 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);