2013-03-26 23 views
1

我是新來的Obj-c。如果成功(Game Center login = success),我有一個將var boolean設置爲YES的類,那麼做什麼是好的,它有一個監聽器,當它是YES時監聽它,然後執行一些代碼。我爲此使用了一個區塊嗎?我也在使用Sparrow框架。在Objective C中使用Block來確定BOOL是否已被設置?

這是我在我的GameCenter.m文件

-(void) setup 
{ 
    gameCenterAuthenticationComplete = NO; 

    if (!isGameCenterAPIAvailable()) { 
     // Game Center is not available. 
     NSLog(@"Game Center is not available."); 
    } else { 
     NSLog(@"Game Center is available."); 

      __weak typeof(self) weakSelf = self; // removes retain cycle error 

      GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer]; // localPlayer is the public GKLocalPlayer 

     __weak GKLocalPlayer *weakPlayer = localPlayer; // removes retain cycle error 

      weakPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) 
      { 
       if (viewController != nil) 
       { 
        [weakSelf showAuthenticationDialogWhenReasonable:viewController]; 
       } 
       else if (weakPlayer.isAuthenticated) 
       { 
        [weakSelf authenticatedPlayer:weakPlayer]; 
       } 
       else 
       { 
        [weakSelf disableGameCenter]; 
       } 
      }; 
     } 

    } 

    -(void)showAuthenticationDialogWhenReasonable:(UIViewController *)controller 
    { 
     [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:controller animated:YES completion:nil]; 
    } 

    -(void)authenticatedPlayer:(GKLocalPlayer *)player 
    { 
     NSLog(@"%@,%@,%@",player.playerID,player.displayName, player.alias); 

     gameCenterAuthenticationComplete = YES; 

    } 

    -(void)disableGameCenter 
    { 

    } 

代碼,但我需要從不同的對象來知道這gameCenterAuthenticationComplete等於YES。

回答

3

您可以使用委託模式。它比KVO或本地通知使用起來要容易得多,而且在Obj-C中使用它很多。

只能在特定情況下使用通知(例如,當您不知道誰想聽或有多於一個聽衆時)。

一個塊可以在這裏工作,但代理人完全一樣。

2

您可以使用KVO(鍵值觀察)來觀察對象的屬性,但我寧願在您的案例中發佈NSNotification。

您需要讓對象有興趣知道Game Center登錄發生的時間,然後將其登錄到NSNotificationCenter,然後將NSNotification發佈到您的Game Center處理程序中。閱讀通知編程主題瞭解更多詳情!

0

如果在單個委託對象上執行單個方法,則只需在setter中調用它即可。我舉一個名字這個屬性:

@property(nonatomic,assign, getter=isLogged) BOOL logged; 

這是不夠,你實現二傳手:

- (void) setLogged: (BOOL) logged 
{ 
    _logged=logged; 
    if(logged) 
     [_delegate someMethod]; 
} 

另一個(建議)的方法是使用NSNotificationCenter。藉助NSNotificationCenter,您可以通知多個對象。希望當屬性更改爲YES執行方法的所有對象必須註冊:

NSNotificationCenter* center=[NSNotificationCenter defaultCenter]; 
[center addObserver: self selector: @selector(handleEvent:) name: @"Logged" object: nil]; 

的爲handleEvent:選擇將每一個記錄更改爲YES時執行。因此,在財產發生變化時發佈通知:

- (void) setLogged: (BOOL) logged 
{ 
    _logged=logged; 
    if(logged) 
    { 
     NSNotificationCenter* center=[NSNotificationCenter defaultCenter]; 
     [center postNotificationName: @"Logged" object: self]; 
    } 
} 
相關問題