Cocoa - Create multiple instance of my application

171 Views Asked by At

My requirement is to create multiple instance of my application. I am able to create multiple instance without argument successfully but as I am passing some argument with my runCommand, it creates infinite instances of my application and to stop this I have to shutdown my System forcefully.

Thanks in advance :

my working code is below :

- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
    isOpenFileFlag = YES;

    NSString *filePathStr = [NSString stringWithFormat:@"open -n /Applications/MyApp.app --args %@",filename];

    [self runCommand:filePathStr];

    return YES;
}

- (NSString *) runCommand: (NSString *) commandToRun {
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects: @"-c" , [NSString stringWithFormat:@"%@", commandToRun], nil];
    NSLog(@"run command: %@",commandToRun);
    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *output;
    output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    return output;

}

Only thing that I have to do is to create multiple instance of my application one by one.

1

There are 1 best solutions below

0
On

Currently you are creating a loop, because every instance that launches, launches another instance and so on.. You have to stop creating instances, when you have enough of them. (Captain Obvious)

I guess there are multiple ways of doing this. You could check how many instances of your app are running at the moment.

Another approach (what I would do): Create a NSNumber object at first launch that you can write to NSPasteBoard. Every other instance loads the number and adds one to it. If you have the right count, stop the loop.