3

私は(基本的に)iOS 4でバックグラウンドタイマーを作成する必要があります。これにより、特定の時間が経過したときにコードを実行できるようになります。いくつかを使用してこれを達成できることを読みました[NSThread detachNewThreadSelector: toTarget: withObject:];が、実際にはどのように機能しますか?スレッドがバックグラウンドにも残っていることを確認するにはどうすればよいですか。ユーザーに通知するのではなく、コードを実行する必要があるため、ローカル通知は機能しません。

助けていただければ幸いです!

4

3 に答える 3

20

Grand Central Dispatch(GCD)を使用してこれを行うこともできます。このようにして、ブロックを使用してコードを1つの場所に保持し、バックグラウンド処理の終了後にUIを更新する必要がある場合は、必ずメインスレッドを再度呼び出すことができます。基本的な例は次のとおりです。

#import <dispatch/dispatch.h>

…

NSTimeInterval delay_in_seconds = 3.0;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delay_in_seconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

UIImageView *imageView = tableViewCell.imageView;

// ensure the app stays awake long enough to complete the task when switching apps
UIBackgroundTaskIdentifier taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:{}];

dispatch_after(delay, queue, ^{
    // perform your background tasks here. It's a block, so variables available in the calling method can be referenced here.        
    UIImage *image = [self drawComplicatedImage];        
    // now dispatch a new block on the main thread, to update our UI
    dispatch_async(dispatch_get_main_queue(), ^{        
      imageView.image = image;
      [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
    });
}); 

グランドセントラルディスパッチ(GCD)リファレンス: http ://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html

ブロックリファレンス: http ://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/index.html%23//apple_ref/doc/uid/TP40009758

バックグラウンドタスクリファレンス: http ://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler :

于 2010-11-14T11:04:57.103 に答える
4

これらの呼び出しを使用して、新しいスレッド(detachNewThred)でいくつかのパラメーター(withObject)を使用してオブジェクト(toTarget)のメソッド(セレクター)を実行できます。

ここで、遅延タスクを実行する場合は最善のアプローチである可能性があり、performSelector: withObject: afterDelay:バックグラウンドでタスクを実行する場合は、detachNewThreadSelector: toTarget: withObject:

于 2010-11-11T12:52:24.107 に答える
0

これらの提案された方法は、アプリケーションが最初にバックグラウンド実行(UIBackgroundModeを使用)に対して有効になっている場合にのみ適用できますか?

アプリケーションがvoip/music / location対応アプリであると合法的に主張できない場合、ここで説明されていることを実装している場合、時間間隔が経過しても実行されないと思いますか?

于 2011-12-05T20:21:33.513 に答える