1

I have a function that sends a string "theData". I want to insert that string here in this code. Would someone please tell me the correct syntax for this? Things get a bit hairy with the \"s and the "s. Thanks!

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/osascript"];
[task setArguments:[NSArray arrayWithObjects:@"-e", @"tell application \"System Events\"\n", 
                                             @"-e", @"    keystroke \"" + theData + "\"", 
                                             @"-e", @"end tell", nil]];
[task launch];
Yuji
  • 34,103
  • 3
  • 70
  • 88
winduptoy
  • 5,366
  • 11
  • 49
  • 67
  • There's probably a much better way to simulate keystrokes with Objective-C... – icktoofay Jul 02 '10 at 02:53
  • 3
    And in fact, it looks like there is. (http://stackoverflow.com/questions/2379867/) – icktoofay Jul 02 '10 at 02:56
  • oooooh, just saw this. it works flawlessly (so far) in 10.6 for me, but could this be a problem? `CGPostKeyboardEvent Deprecated in Mac OS X v10.6` http://developer.apple.com/mac/library/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple%5Fref/c/func/CGEventKeyboardSetUnicodeString – winduptoy Jul 03 '10 at 01:44
  • Use CGEventCreateKeyboardEvent: http://developer.apple.com/mac/library/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/doc/uid/TP40003550-CH202-BBCFIDCH (Also see this: http://stackoverflow.com/questions/2008126/cgeventpost-possible-bug-when-simulating-keyboard-events/2079649#2079649 ) – has Jul 04 '10 at 07:45

2 Answers2

1

icktoofay already gave the more correct answer, but let me just show how to insert a string in a string:

       NSString* toBeInserted = @"for";
       NSString* result = [NSString stringWithFormat:@"in%@mation",toBeInserted]; 
       NSLog(@"%@",result);

This gives information. For more details, read Apple's doc.

I mean, Apple's doc is quite good, actually. Read it before asking a question here at SO.

By the way, you don't have to launch osascript to execute AppleScript. You can use NSAppleScript as in

NSAppleScript* script=[[NSAppleScript alloc] initWithSource:@"tell app \"Finder\" to activate "];
NSDictionary*error;
[script executeAndReturnError:&error];
[script release];

Well, NSAppleScript is an oddity which requires NSDictionary, not an NSError, to report an error ...

Or, you can use Scripting Bridge to map AppleScript objects to Objective-C objects.

Yuji
  • 34,103
  • 3
  • 70
  • 88
0

I see you have another way of doing it, but you can use format strings to accomplish this

[NSString stringWIthFormat: @"part one %@ part 2", theData];

Assuming the data is an nsstring containing "hello", this will give you:

@"part one hello part 2"
Tom H
  • 1,316
  • 14
  • 26