我是比較新的可可/ 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
}
}
但是,這是非常醜陋的,不是線程安全的。 這樣做的正確方法是什麼?
謝謝,
你能告訴我有什麼好處呢對任何人你的代碼的一個虛構的例子嗎?我不得不說,這與把你的鄰居的車帶到機械師差不多,因爲你的東西有問題。 – Sneakyness 2009-07-26 18:50:34
使用簡單的遊戲比喻更容易說明我的設計問題,而不是解釋我正在開發的應用程序的某些複雜功能。 – tba 2009-07-26 19:06:27