2009-07-26 43 views
1

我是比較新的可可/ ObjC。有人可以幫我改變我的代碼來使用異步網絡調用嗎?目前,它看起來像這樣(例如虛構):回調在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:...委託:...]實施回調做後期處理。這是我能想到的唯一方法:

//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 
    } 
} 

但是,這是非常醜陋的,不是線程安全的。 這樣做的正確方法是什麼?

謝謝,

+0

你能告訴我有什麼好處呢對任何人你的代碼的一個虛構的例子嗎?我不得不說,這與把你的鄰居的車帶到機械師差不多,因爲你的東西有問題。 – Sneakyness 2009-07-26 18:50:34

+1

使用簡單的遊戲比喻更容易說明我的設計問題,而不是解釋我正在開發的應用程序的某些複雜功能。 – tba 2009-07-26 19:06:27

回答

1

一種選擇是具有每個命令/請求的一個對象實例;作爲額外的獎勵,你可以使用子類來處理類型,而不是基於大的switch語句。使用initWithDelegate:方法創建一個基本命令對象(然後在與需要參數的命令對應的子類中有專門的入口)以及基本發送/接收管道的方法。每個子類都可以實現一個handleResponse:或從你的基類connectionDidFinishLoading:中調用的類似。

如果要隱藏,從這個服務,你的攻擊:,的moveTo:等的客戶方法可以隱藏這些對象的實例化,所以客戶端將與相同的API進行交互。