lab12
lab12

Reputation: 6448

NSRunningApplication - Terminate

How would I use NSRunningApplication? I have something opposite of that which is launching an app:

[[NSWorkspace sharedWorkspace] launchApplication:appName];

but I want to close one. I get an error when I debug the code for NSRunningApp which is this:

NSRunningApplication *selectedApp = appName;
[selectedApp terminate];

Is there something wrong? if there is please point it out and how to fix it.

Upvotes: 2

Views: 5042

Answers (2)

Georg Schölly
Georg Schölly

Reputation: 126085

You assign the variable selectedApp a NSString. Strings don't have the - (void)terminate method and therefore it fails. You have to get a NSRunningApplication instance pointing to the application.

NSWorkspace *sharedWorkspace = [NSWorkspace sharedWorkspace];
NSString *appPath = [sharedWorkspace fullPathForApplication:appName];
NSString *identifier = [[NSBundle bundleWithPath:appPath] bundleIdentifier];
NSArray *selectedApps =
       [NSRunningApplication runningApplicationsWithBundleIdentifier:identifier];
// quit all
[selectedApps makeObjectsPerformSelector:@selector(terminate)];

Upvotes: 8

Alex Rozanski
Alex Rozanski

Reputation: 38005

What does appName refer to? If it literally refers to an NSString then that will not work.

Since NSRunningApplication is a class, you have to create an instance to send it an instance method as you would with any other class.

There are three class methods (see the docs) you can use to return an NSRunningApplication instance:

+ runningApplicationWithProcessIdentifier:
+ runningApplicationsWithBundleIdentifier:
+ currentApplication

Unless you want an NSRunningApplication instance based on the current application you are likely to find the first two class methods most useful.

You can then send the terminate message to the NSRunningApplication instance, which will attempt to quit the application that it has been configured for.

Upvotes: 5

Related Questions