NSMachBootstrapServer 已弃用,如何使用 NSXPCConnection 注册 Mach 服务?

NSMachBootstrapServer is deprecated, how can NSXPCConnection be used to register a Mach Service?

我需要编写一个 Mach 服务,我的应用程序和系统插件都可以与之通信,我使用 NSMachPort API 创建一个新端口,然后用 [=13 注册它=]:

- (void) run
{
    NSMachPort *serverPort = (NSMachPort *)[NSMachPort port];
    [serverPort setDelegate:self];
    [serverPort scheduleInRunLoop:NSRunLoop.currentRunLoop forMode:NSDefaultRunLoopMode];
    [NSMachBootstrapServer.sharedInstance registerPort:serverPort name:@"com.example.MyApp"];

    [NSRunLoop.currentRunLoop run];
}

Clang 抱怨 NSMachBootstrapServer 已被弃用:

warning: 'NSMachBootstrapServer' is deprecated: first deprecated in macOS 10.13 - Use NSXPCConnection instead

如何在编写非 XPC mach 服务时使用 NSXPCConnection 替换 NSMachBootstrapServer 的功能?

没错:NSMachBootstrapServer class 及其大部分 classes 是 deprecated 在 macOS 10.13 High Sierra 中。

In macOS 10.14 Mojave and higher you have to use a NSXPCConnection API, that is the Foundation module's part. It's described in the header file NSXPCConnection.h. At the moment it consists of the four main classes:

XPC 连接过程如下所示:

正如您在图片上看到的那样,您必须实现一个侦听器。

下面是带有侦听器的 Swift 代码片段的样子:

let listener = NSXPCListener(machServiceName: "Name-of-Sample.Helper")
listener.delegate = delegate
listener.resume()
RunLoop.current.run()

下面是带有侦听器的 Obj-C 代码片段的样子:

self.listener = [[NSXPCListener alloc] initWithMachServiceName:@"Name-of-Sample.Helper"];
self.listener.delegate = self;
[self.listener resume];
[[NSRunLoop currentRunLoop] run];

If you look at you'll find out how to properly implement all the necessary XPC Connection's objects.

和...

If you look at This Post you'll also find out how it can be used with a Mach Service (there's GitHub link).