NSRunningApplication Completion

How to use NSRunningApplication

? I have something opposite of what the application launches:

[[NSWorkspace sharedWorkspace] launchApplication:appName];

      

but I want to close it. I am getting an error when debugging code for NSRunningApp

that:

NSRunningApplication *selectedApp = appName;
[selectedApp terminate];

      

Is there something wrong? if there is, please indicate it and how to fix it.

+2


source to share


2 answers


You are assigning to variable selectedApp

a NSString

. Strings don't have a method - (void)terminate

and so it fails. You should get an instance NSRunningApplication

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)];

      

+8


source


What does it mean appName

? If that literally means NSString

, then it won't work.

Since it NSRunningApplication

is a class, you need to create an instance to send an instance method to it, just like with any other class.

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

:



+ runningApplicationWithProcessIdentifier:
+ runningApplicationsWithBundleIdentifier:
+ currentApplication

      

If you don't need an instance NSRunningApplication

based on the current application, you will most likely find the first two classes that work best.

You can then send a message terminate

to the instance NSRunningApplication

, which will try to close the application for which it is configured.

+5


source







All Articles