@implementation SomethingConnectingToRemoteObject - (oneway void)connectNew { NSArray *args; if(simulator) { [NSException raise:@"AFDistantSimulatorException" format:@"Simulator is already connected"]; return; } if(serverTask) { /* Just in case, terminate the server task */ [[NSNotificationCenter defaultCenter] removeObserver:self name:NSTaskDidTerminateNotification object:serverTask]; [serverTask terminate]; RELEASE(serverTask); serverTask = nil; } ASSIGN(checkTime,[NSDate date]); args = [NSArray arrayWithObjects: @"-AFUserIdentifier", identifier, nil]; serverTask = [[NSTask alloc] init]; [serverTask setLaunchPath:@"afsimulator"]; [serverTask setArguments:args]; [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_connectSimulator:) name:@"AFDistantSimulatorConnectNotification" object:identifier]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_taskTerminated:) name:NSTaskDidTerminateNotification object:serverTask]; [serverTask launch]; NSLog(@"%@", serverTask); } - (void)_connectSimulator:(NSNotification *)notif { NSDictionary *dict = [notif userInfo]; NSString *serverName; serverName = [dict objectForKey:@"AFDistantSimulatorName"]; /* We have received desired notification, therefore we should unregister ourselves */ [[NSDistributedNotificationCenter defaultCenter] removeObserver:self]; NSLog(@"Connection requested to %@", serverName); [self _connectToServerWithName:serverName]; } - (void)_connectToServerWithName:(NSString *)serverName { simulator = (NSDistantObject *)[NSConnection rootProxyForConnectionWithRegisteredName:serverName host:nil]; if(!simulator) { [NSException raise:@"AFDistantSimulatorException" format:@"Unable to get distant simulator object from server '%@'", serverName]; return; } RETAIN(simulator); [(NSDistantObject *)simulator setProtocolForProxy:@protocol(AFSimulator)]; NSLog(@"Found simulator. Class: %@.", [(NSObject *)simulator className]); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_connectionDidDie:) name:NSConnectionDidDieNotification object:[simulator connectionForProxy]]; NSLog(@"Connection time: %f", -[checkTime timeIntervalSinceNow]); [[NSNotificationCenter defaultCenter] postNotificationName:AFDistantSimulatorConnectedNotification object:self]; } @end