代码之家  ›  专栏  ›  技术社区  ›  Richard J. Ross III

iOS4创建后台计时器

  •  3
  • Richard J. Ross III  · 技术社区  · 14 年前

    我(基本上)需要在iOS 4上创建一个后台计时器,它允许我在经过特定时间后执行一些代码。我听说你可以用一些 [NSThread detachNewThreadSelector: toTarget: withObject:]; 但这在实践中是如何运作的呢?如何确保线程也保留在后台。本地通知将 不是 为我工作,因为我需要执行代码,而不是通知用户。

    希望您能帮忙!

    3 回复  |  直到 14 年前
        1
  •  4
  •   Richard J. Ross III    13 年前

    可以使用这些调用在新线程(detachNewThred)中使用某些参数(with object)执行对象(toTarget)的方法(选择器)。

    现在如果你想执行一个延迟的任务,最好的方法是 performSelector: withObject: afterDelay: 如果要在后台运行任务,请调用 detachNewThreadSelector: toTarget: withObject:

        2
  •  20
  •   mrwalker    13 年前

    您也可以使用Grand Central Dispatch(GCD)完成此操作。这样,您可以使用块将代码保存在一个地方,并且确保在完成后台处理后需要更新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];
        });
    }); 
    

    Grand Central Dispatch(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 :

        3
  •  0
  •   Piepants    13 年前

    这些建议的方法是否仅在应用程序首先启用后台执行(使用UIBackgroundMode)时才适用?

    我假设如果一个应用程序不能合法地声明是一个voip/音乐/位置感知应用程序,那么如果它实现了这里描述的内容,那么当时间间隔到期时它将不会执行?

    推荐文章