2011-10-23 25 views
0

我必須從另一個應用程序爲android創建一個iDevice應用程序。我只需要顯示一個對話框,只需兩秒鐘。在Android的我使用此代碼:如何在objective-c中創建處理程序-c

public class ThreadW extends Thread{ 
    private Handler handler; 
    public ThreadW(Handler handler){ 
     this.handler=handler; 
    } 
    public void run(){ 
     notifyM("start"); 
     Thread.sleep(2500); 
     notifyM("stop"); 
    } 
    private void notifyM(String message){ 
     Message msg = handler.obtainMessage(); 
     Bundle b = new Bundle(); 
     b.putString("Dialog", message); 
     msg.setData(b); 
     handler.sendMessage(msg); 
    } 
} 

和Handler:

public class HandlerWelcome extends Handler { 
    private DialogWelcome w; 
    private Context c ; 
    public HandlerWelcome(Context c){ 
     this.c=c; 
    } 
    public void handleMessage(Message msg) { 
     Bundle bundle = msg.getData(); 
     if(bundle.getString("Dialog").equals("start")){ 
      w = new DialogWelcome(c); 
      w.show(); 
     }else if(bundle.getString("Dialog").equals("stop")) 
      w.cancel(); 
    } 
} 

我用所有以這種方式:

ThreadW tw = new Thread(new HandlerWelcome(c)); 
tw.start(); 

我如何可以做同樣的目標C?

回答

2

下面是使用Grand Central Dispatch(GCD)的解決方案:

// Call this method on the main thread 
- (void)showWelcomeMessage 
{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Welcome" 
                message:@"Have a nice day!" 
                delegate:nil 
              cancelButtonTitle:nil 
              otherButtonTitles:nil]; 
    [alert show]; 

    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*2.0); 
    dispatch_after(delay, dispatch_get_main_queue(), ^{ 
     [alert dismissWithClickedButtonIndex:0 animated:YES]; 
    }); 

    [alert release]; 
} 

然而,你應該創建一個自定義警告對話框,因爲iOS用戶不會期待一個標準警報對話框自動消失。

+1

這就是我需要的!非常感謝你!! :)另一個問題,在這dispatch_after,我可以把其他方法,如調用另一個視圖? – JackTurky

+1

此代碼將泄漏,您需要釋放警報或使警報成爲autorelease對象。除非你在主線程中,否則你不應該做任何與UI相關的東西。因此,你應該把[alert dismissWith ...]換成類似的東西; [self performSelectorOnMainThread:@selector(updateDone :) withObject:alert waitUntilDone:NO]; updateDone然後執行:[alert dismissWithClickedButtonIndex:0 animated:YES]; [警報發佈]; – jyavenard

+1

@jyavenard在ARC之下它不會泄漏。如果你不使用ARC,你應該確實調用''alert autorelease''。此外,調用任何'dispatch_XXX'函數到主隊列上意味着它將在主線程上執行,因此在那裏進行UI更新是安全的。 –

1

你應該看看NSTimer類。它將允許您設置特定目標和選擇器的延遲執行(該對象上的對象和方法)。像scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:這樣的方法可能是你需要的。

查看class documentation on the Apple developer site的全部細節。

相關問題