1. protocl 协议

这个是类似于 java 等面向对象编程语言中的 接口。

在 Obejct-C 中接口主要由 协议 组成。

程序中 我们的

XPCDemoProtocl.h

//
//  XPCDemoProtocol.h
//  XPCDemo
//
//  Created by 骆驼 on 2022/2/8.
//

#import <Foundation/Foundation.h>

// The protocol that this service will vend as its API. This header file will also need to be visible to the process hosting the service.
@protocol XPCDemoProtocol

// Replace the API of this protocol with an API appropriate to the service you are vending.
- (void)upperCaseString:(NSString *)aString withReply:(void (^)(NSString *))reply;
    
@end

/*
 To use the service from an application or other process, use NSXPCConnection to establish a connection to the service by doing something like this:

     _connectionToService = [[NSXPCConnection alloc] initWithServiceName:@"com.0xc4m3l.XPCDemo"];
     _connectionToService.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(XPCDemoProtocol)];
     [_connectionToService resume];

Once you have a connection to the service, you can use it like this:

     [[_connectionToService remoteObjectProxy] upperCaseString:@"hello" withReply:^(NSString *aString) {
         // We have received a response. Update our text field, but do it on the main thread.
         NSLog(@"Result string was: %@", aString);
     }];

 And, when you are finished with the service, clean up the connection like this:

     [_connectionToService invalidate];
*/

这个协议定义了 一个接口 - (void)upperCaseString:(NSString *)aString withReply:(void (^)(NSString *))reply;

其中 需要让程序调用的方法,我们必须在 protocl 中指定。

XPC 通信是异步的,因此 protocol 中的方法的返回值都只能是 void,如果需要返回数据则使用返回块,即正如上面代码中 upperCaseString 函数的第二个参数,类似于 callback。

2. 协议接口函数实现 interface

因为我们创建的 协议文件名叫 XPCDemoProtocol.h 这里 我们就需要在 XPCDemo.m 文件中去对协议进行一个 实现

切我们要定义 继承这个 protocl

对应的这个类的 头文件中定义

//  XPCDemo.h

#import <Foundation/Foundation.h>
#import "XPCDemoProtocol.h"

// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection.
@interface XPCDemo : NSObject <XPCDemoProtocol>
@end

然后功能实现在 XPCDemo.m

//  XPCDemo.m

#import "XPCDemo.h"

@implementation XPCDemo

// Thiccccxs implements the example protocol. Replace the body of this class with the implementation of this service's protocol.
- (void)upperCaseString:(NSString *)aString withReply:(void (^)(NSString *))reply {
    NSString *response = [aString uppercaseString];
    reply(response);
}

@end

这里的 upperCaseString 函数只做了一件事情:将传入的字符串全部转换为大写,并调用 callback 将结果返回