2010-12-02 66 views
1

大家。 我想了解,当异步方法具有“didFinish:@selector(SEL)”参数时,我应该如何处理这种情况。 我的代码示例:如何等待iPhone应用程序中的异步方法完成?

// 
// Authentication check 
- (void)authenticationSuccess: (GDataServiceTicket*) ticket 
     authenticatedWithError: (NSError*) error { 

    if (error == nil) 
    { 
     NSLog(@"authentication success"); 
    } 
    else 
    { 
     NSLog(@"authentication error"); 
    } 
} 
// 

- (void) fetchFeedOfSpreadsheets { 

    //create and authenticate to a google spreadsheet service 
    if (!(mService)) 
    { 
     GDataServiceGoogleSpreadsheet *service = [self spreadsheetService]; 
     [mService autorelease]; 
     mService = [service retain];  
    } 

    // check autentication success (invoke "authenticationSuccess" method for debug success & error) 
    [mService authenticateWithDelegate: self 
       didAuthenticateSelector:@selector(authenticationSuccess: 
               authenticatedWithError:) ]; 


    // HERE I WANT TO MAKE A PAUSE AND WHAIT THE RESULT, EITHER I AUTHENTICATED OR NOT 
    // AND MAKE AN "IF" STATEMENT TO CONTINTUE WORKING ON SERVER, OR RETURN ERROR 


    //fetch retrieves the feed of spreadsheets entries 
    NSURL *feedURL = [ NSURL URLWithString: kGDataGoogleSpreadsheetsPrivateFullFeed ]; 
    GDataServiceTicket *ticket; 
    ticket = [mService fetchFeedWithURL: feedURL 
           delegate: self 
         didFinishSelector: @selector(spreadsheetsTicket:finishedWithFeed: 
                error:) ]; 

    // HERE I WANT TO WAIT SECOND TIME. I WANT "spreadsheetsTicket:   
    // finishedWithFeed:error:" TO PROCCEED ERROR AND PUT A FEED IN SOME NSARRAY OBJECT 
    // AND AFTER THAT I WANT TO WORK WITH THAT NSARRAY RIGHT HERE 
} 

我的清楚,我可以把我想成“authenticationSuccess”方法节结束的代码,但它也很清楚,这是一个错误的一个解决proble方式。有很多这样的情况,我调用一个选择器参数的异步方法,我想找到一个解决方案,为我提供了一个灵活的代码编写。

在此先感谢。

回答

2

Objective-C中的一个标准做法是将代码在authenticationSucess:方法中的认证之后执行。你可能不喜欢它,但这就是生活。

很多人有同样的抱怨,你,所以 在iOS 4及更高版本,有一些所谓的块,让你可以把代码写在认证发起该方法的认证后执行,如

[mService authenticateAndExecute:^{ 
       code to be executed when successfully authenticated ; 
      }   whenError:^{ 
       code to be executed when authentication failed; 
      } ]; 

但是在这种情况下,您需要修改API,这可以通过使用类别来实现。见Mike Ash的this blog post。他在同一个博客上有很多其他帖子,这些帖子也非常具有启发性。

+0

谢谢你的回答,Yuji。 – zkaje 2010-12-02 14:46:44

0

如果你打算使用异步工作的库(因此不会阻塞你的UI),你应该有一个很好的理由试图强制它同步工作。

您应该在authenticationSuccess:authenticatedWithError:方法末尾检查身份验证错误,如果成功,请从那里调用下一个请求。同样,在您的spreadsheetsTicket:finishedWithFeed:error:中检查是否有错误,如果没有,则继续处理。用一种单独的方法继续工作可能是一个更好的设计,但这取决于你。

是否有一个特定的原因,你想以同步方式使用GData API?