【问题标题】:NSOperationQueue with a timer带有计时器的 NSOperationQueue
【发布时间】:2012-12-13 15:12:16
【问题描述】:

我想使用一个NSOperationQueue,它里面有一个计时器。 例如 - 我下载了 1 个元素(完成第一个 NSOperation)然后我想等待 3 秒编译器继续进行下一个操作。在第二个NSOperation 完成后,我希望它等待同样的 3 秒,然后开始第 3 次操作。

如何实现这种行为?我之前没有使用过NSTimerNSRunLoop 的经验,我不确定是否应该使用它们。

提前致谢。

【问题讨论】:

    标签: iphone objective-c ios xcode nsoperationqueue


    【解决方案1】:

    只要操作在后台线程中执行;

    您可以将 maxConcurrentOperationCount 设置为 1 并在您的操作块中使用 sleep(3) 3 秒。

    【讨论】:

      【解决方案2】:

      使用sleep(int secondsToSleep);

      【讨论】:

        【解决方案3】:

        如果您只想在操作完成某些操作后等待 3 秒,则只需使用 sleep 和 maxConcurrentOperationCount 即可。

        如果您需要更复杂的内容,您可以在 while 循环中使用 timeIntervalSinceDate。如果您的操作执行一些可能需要不确定时间的处理(在我的情况下,我需要运行远程创建帐户过程)并且您希望在运行下一个操作之前等待至少或最多 X 秒,这将非常有用队列。您可以使后续的 NSOperations 依赖于先前操作的完成。

        使用 addDependency 对 NSOperation 进行排序以等待上一个操作完成:

        NSOperationQueue *ftfQueue = [NSOperationQueue new];
        // Does this user have an account?
        // createFTFAccount is subclass of NSOperation.  
        FTFCreateAccount *createFTFAccount = [[FTFCreateAccount alloc]init];
        [createFTFAccount setUserid:@"a-user-id"];
        [ftfQueue addOperation:createFTFAccount];
        // postFTFRoute subclass NSOperation    
        FTFPostRoute *postFTFRoute = [[FTFPostRoute alloc]init];
        // Add postFTFRoute with a dependency on Account Creation having finished 
        [postFTFRoute addDependency:createFTFAccount];
        [ftfQueue addOperation:postFTFRoute];
        

        在 NSOperation 子类主检查操作是否已完成或耗时过长

        #import <Foundation/Foundation.h>
        @interface FTFCreateAccount : NSOperation
            @property (strong,nonatomic) NSString *userid;
        @end    
        
        
        
        @implementation FTFCreateAccount
        {
            NSString *_accountCreationStatus;
        }
        
        - (void)main {
        
            NSDate *startDate = [[NSDate alloc] init];
            float timeElapsed;
            ..... 
            .....
            .....
        
            // Hold it here until a reply comes back from the account creation process 
            // Or the process is taking too long
            while ((!_accountCreationStatus) && (timeElapsed < 3.0)) {
                NSDate *currentDate = [[NSDate alloc] init];            
                timeElapsed = [currentDate timeIntervalSinceDate:startDate];
            }
            // Code here to do something dependent on _accountCreationStatus value
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-18
          • 2012-07-07
          • 1970-01-01
          • 2013-09-12
          • 2017-05-02
          • 2016-03-21
          • 2012-08-03
          相关资源
          最近更新 更多