Launching external apps and waiting for them to launch
I'm trying to launch a list of supporting apps. I then have to wait until those apps have finished launching before continuing to execute code. Here is what I have right now:
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
int i = 0;
while (i < [launchApps count]) {
[ws launcApplication: [launchApps objectAtIndex: i]];
++i
}
while (![self appsFinishedLaunching]) {
NSLog(@"loop");
sleep(1);
}
then later:
- (BOOL)appsFinishedLaunching
{
BOOL doneLaunching = NO;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i = 0;
while (i < [launchApps count]) {
NSWorkspace *nws = [NSWorkspace sharedWorkspace];
NSA开发者_Python百科rray *runningApps = [NSArray arrayWithArray:[nws runningApplications]];
for (NSRunningApplication *app in runningApps) {
if ([[app localizedName] isEqualToString:[launchApps objectAtIndex:i]]) {
if ([app isFinishedLaunching]) {
[launchApps removeObjectAtIndex:i];
break;
}
}
}
++i;
}
if ([launchApps count] == 0)
doneLaunching = YES;
[pool drain];
return doneLaunching;
}
If I run manually open all the Apps in launchApps I get one "loop" in console and all is well. If I run this code and let it launch the apps it goes in to an infinite loop. It seems like the NSRunningApplications objects in my shared workspace aren't being updated and I'm not sure I understand why. What am I missing?
From the Apple Docs on NSRunningApplication:
@property(readonly, getter=isFinishedLaunching) BOOL finishedLaunching
The value of this property corresponds to the running application having received an NSApplicationDidFinishLaunchingNotification notification internally. Some applications do not post this notification (applications that do not rely on NSApplication) and so are never reported as finished launching.
If the application you've launched doesn't post the notification, you can't use this property.
The question is, is the application you're trying to launch a Cocoa app? If not, you might have to investigate other launching functions; the C function exec
might work, but I haven't looked into it.
精彩评论