ObjC + Cocoa中的回调

时间:2009-07-26 18:40:52

标签: iphone objective-c cocoa events refactoring

我对Cocoa / ObjC比较陌生。有人可以帮我改变我的代码以使用异步网络电话吗?目前它看起来像这样(虚构的例子):

// Networker.m
-(AttackResult*)attack:(Charactor*)target {
    // prepare attack information to be sent to server
    ServerData *data = ...;
    id resultData = [self sendToServer:data];
    // extract and return the result of the attack as an AttackResult
}

-(MoveResult*)moveTo:(NSPoint*)point {
    // prepare move information to be sent to server
    ServerData *data = ...;
    id resultData = [self sendToServer:data];
    // extract and return the result of the movement as a MoveResult
}


-(ServerData*)sendToServer:(ServerData*)data {
    // json encoding, etc
    [NSURLConnection sendSynchronousRequest:request ...]; // (A)
    // json decoding
    // extract and return result of the action or request
}

请注意,对于每个操作(攻击,移动等),Networker类都具有与ServerData进行转换的逻辑。期望我的代码中的其他类处理此ServerData是不可接受的。

我需要让A行成为异步调用。看来正确的方法是使用[NSURLConnection connectionWithRequest:... delegate:...]实现回调来做后处理。这是我能想到的唯一方法:

//Networker.m
-(void)attack:(Charactor*)target delegate:(id)delegate {
    // prepare attack information to be sent to server
    ServerData *data = ...;
    self._currRequestType = @"ATTACK";
    self._currRequestDelegate = delegate;
    [self sendToServer:data];
    // extract and return the result of the attack
}

-(void)moveTo:(NSPoint*)point delegate:(id)delegate {
    // prepare move information to be sent to server
    ServerData *data = ...;
    self._currRequestType = @"MOVE";
    self._currRequestDelegate = delegate;
    [self sendToServer:data];
    // extract and return the result of the movement
}


-(void)sendToServer:(ServerData*)data {
    // json encoding, etc
    [NSURLConnection connectionWithRequest:...delegate:self] // (A)
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //json decoding, etc
    switch( self._currRequestType ) {
        case @"ATTACK": {...} // extract and return the result of the attack in a callback
        case @"MOVE": {...} // extract and return the result of the move in a callback
    }
}

但是,这非常难看并且不是线程安全的。 这样做的正确方法是什么?

谢谢,

1 个答案:

答案 0 :(得分:1)

一个选项是每个命令/请求有一个对象实例;作为额外的奖励,您可以使用子类,以便类型的处理是多态的,而不是基于一个大的switch语句。使用initWithDelegate:方法创建一个基本命令对象(然后在对应于需要参数的命令的子类中具有专门的inits)和基本发送/接收管道的方法。每个子类都可以实现一个handleResponse:或类似的从你的基类connectionDidFinishLoading调用:。

如果你想从这个服务的客户端隐藏它,你的attack:,moveTo:等方法可以隐藏这些对象的实例化,因此客户端将与相同的API进行交互。