Iphone 使用委托时,需要更好的方法来执行顺序处理
我有一个类WebServiceCaller,它使用NSURLConnection对web服务进行异步调用。该类提供一个委托属性,当web服务调用完成时,它调用委托上的方法webServiceDoneWithXXX 可以调用几种web服务方法,其中两种是GetSummary和GetList 使用WebServiceCaller的类最初需要摘要和列表,因此它们的编写方式如下:Iphone 使用委托时,需要更好的方法来执行顺序处理,iphone,objective-c,cocoa-touch,asynchronous,delegates,Iphone,Objective C,Cocoa Touch,Asynchronous,Delegates,我有一个类WebServiceCaller,它使用NSURLConnection对web服务进行异步调用。该类提供一个委托属性,当web服务调用完成时,它调用委托上的方法webServiceDoneWithXXX 可以调用几种web服务方法,其中两种是GetSummary和GetList 使用WebServiceCaller的类最初需要摘要和列表,因此它们的编写方式如下: -(void)getAllData { [webServiceCaller getSummary]; } -(voi
-(void)getAllData {
[webServiceCaller getSummary];
}
-(void)webServiceDoneWithGetSummary {
[webServiceCaller getList];
}
-(void)webServiceDoneWithGetList {
...
}
这是可行的,但至少存在两个问题:
我还没试过这个。这似乎比使用状态变量和if-then语句要好,但您必须编写更多的方法。我仍然没有看到问题1的解决方案。确实,获取web服务调用的结果是(并且应该是)异步的,但是,您希望调用按顺序进行。一种方法是在调用第二个之前等待第一个完成,并在第一个完成后发布通知。因此,在您的第一个请求的-connectiondFinishLoading中(我假设是在您的webServiceCaller中),向控制器发回一个通知,告诉它第一个请求已成功完成。比如:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
// receivedData is an NSMutableData object we've been appending
// to in the -didReceiveData delegate. We'll pass it in the
// notification so we can hand the data off to the next request.
[[NSNotificationCenter defaultCenter]
postNotificationName:kGetSummaryDidFinish object:receivedData];
}
然后,回到控制器中,注册该通知:
- (void)viewDidLoad;
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getSummaryDidFinish:)
name:kGetSummaryDidFinish object:nil];
}
- (void) getSummaryDidFinish:(NSNotification*)notification;
{
// If you needed the downloaded data, we passed it in
NSData *data = [notification object];
// Decide here if you want to call getList or not.
if (someConditionOfDataObjectIsTrue)
[webServiceCaller getList];
}
如果你有很多这样的等待,它会变得非常混乱和难以维护,所以可能有一个你应该考虑的设计模式(而不是此刻想到的)。然而,这种方法对我来说非常有效。通知有助于使其更有意义,因为当您收到满足某些条件的通知时,您可以从控制器调用所有请求
希望这有意义。谢谢你的回答。我已经看过了,它似乎不能解决一个地方的排序问题(除非我遗漏了什么),但它确实给了我解决第二个问题的想法。我将更新问题,说明我认为如何使用通知解决它(问题2)。如果看起来对的话,请告诉我。
- (void)viewDidLoad;
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getSummaryDidFinish:)
name:kGetSummaryDidFinish object:nil];
}
- (void) getSummaryDidFinish:(NSNotification*)notification;
{
// If you needed the downloaded data, we passed it in
NSData *data = [notification object];
// Decide here if you want to call getList or not.
if (someConditionOfDataObjectIsTrue)
[webServiceCaller getList];
}