Daemons and Services Programming Guides告诉您,可以通过打开的XPC连接返回代理对象,甚至作为应答块参数。
通过代理传递对象
大多数情况下,复制对象并将它们发送到连接的另一端是有意义的。然而,这并不总是可取的。特别是: 如果需要在客户端应用程序和助手之间共享数据的单个实例,则必须通过代理传递对象。如果一个对象需要调用您的应用程序中的其他对象上的方法,而您不能或不希望通过连接传递方法(例如用户界面对象),那么您必须通过代理传递一个对象--调用者、被调用者(如果可能的话),或者专门为此目的构建的中继对象。通过代理传递对象的缺点是性能明显降低(因为对对象的每次访问都需要进程间通信)。因此,只有在无法通过复制传递对象时,才应该通过代理传递对象。 可以配置其他代理对象,类似于配置初始连接的remoteObjectInterface属性的方式。首先,确定哪个参数应该由代理传递给方法,然后指定一个定义该对象接口的NSXPCInterface对象。
第一个问题是:如何定义通过代理传递的对象?作为一个符合NSXPCProxyCreating协议的对象?那么应该实现remoteObjectProxy和remoteObjectProxyWithErrorHandler:方法吗?
下面是一个例子,我一点也不清楚。特别是,我不明白应该在哪里调用(setInterface:forSelector:argumentIndex:ofReply:)方法NSXPCInterface来将参数白化为代理:在XPC服务代码中还是在主机中?
方法的第一个参数是参数0,后面是参数1,依此类推。 在本例中,ofReply参数的值NO被传递,因为这段代码正在修改方法本身的一个参数的白名单。如果要为该方法的reply块的参数白名单类,则传递YES。
因此,问题是:有人能为我提供一个明确的教程,说明如何在XPC方法调用的块答复中将对象作为代理返回吗?
发布于 2013-02-02 16:03:43
我现在可以回答我自己的问题:要在XPC方法调用的块答复中将对象作为代理返回,应该同时调用setInterface:forSelector:argumentIndex:ofReply:方法:
exportedInterfaceremoteObjectInterface即共同代码:
// common (service/host) protocol definition
@protocol Service
@end
@protocol ServiceFactory
-(void)connectToNewService: (void (^)(id<Service>)reply;
@end在XPC服务中:
// Implement the one method in the NSXPCListenerDelegate protocol.
-(BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection*)newConnection {
NSXPCInterface *serviceFactoryInterface =[NSXPCInterface interfaceWithProtocol:@protocol(ServiceFactory)];
NSXPCInterface *serviceInterface =[NSXPCInterface interfaceWithProtocol:@protocol(Service)];
// connection has to be returned as proxy, not as a copy
[serviceFactoryInterface setInterface: serviceInterface
forSelector: @selector(connectToNewService:)
argumentIndex: 0
ofReply: YES];
newConnection.exportedInterface = serviceFactoryInterface;
newConnection.exportedObject = self;
[newConnection resume];
return YES;
}在主机代码中:
// in the host
- (void)openNewService
{
NSXPCConnection *xpcConnection = [[NSXPCConnection alloc] initWithServiceName:@"eu.mycompany.servicefactory"];
NSXPCInterface *serviceFactoryInterface =[NSXPCInterface interfaceWithProtocol:@protocol(ServiceFactory)];
NSXPCInterface *serviceInterface =[NSXPCInterface interfaceWithProtocol:@protocol(Service)];
// connection has to be returned as proxy, not as a copy
[serviceFactoryInterface setInterface: serviceInterface
forSelector: @selector(connectToNewService:)
argumentIndex: 0
ofReply: YES];
xpcConnection.remoteObjectInterface = serviceFactoryInterface;
[xpcConnection resume];
[[xpcConnection remoteObjectProxy] connectToNewService:^(id<Service> newService) {
// here a newService is returned as NSXPCDistantObject <Service>*
[xpcConnection invalidate];
}];
}https://stackoverflow.com/questions/14661375
复制相似问题