views:

47

answers:

2

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];
+1  A: 

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
A: 

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