我想继续处理图像并在iOS App后台存储它

时间:2014-02-16 07:27:36

标签: ios background nsoperation nsoperationqueue

我尝试使用NSOperation和NSOperationQueue 但随着进入背景,NSOperation没有奏效。它停了。

调用

- (void)viewDidLoad
{
    findFQueue = [[NSOperationQueue alloc] init];
    FindFeatureOperation *testOperation = [[FindFeatureOperation alloc] init];
    [findFQueue addOperation:testOperation];
}

NSOperation定义

#import "FindFeatureOperation.h"

@implementation FindFeatureOperation
- (void)main
{
for (int i = 0; i < 999999 ; i++) {
    NSLog(@"Operation %d", i);
    [NSThread sleepForTimeInterval:1];
}
}
@end

让我知道。

1 个答案:

答案 0 :(得分:1)

1路:在op

继续执行操作:

- (main) {
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    for (int i = 0; i < 999999 ; i++) {
        NSLog(@"Operation %d", i);
        [NSThread sleepForTimeInterval:1];
    }

    [application endBackgroundTask];
}

2路:使用applicationDidEnterBG内部:

- (void)applicationDidEnterBackground:(UIApplication *)app {
    _bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
         // When Expired the limit time for background NSLog(@"Expired Background Task Limit Time");
             [app endBackgroundTask:_bgTask]; 
            _bgTask = UIBackgroundTaskInvalid;
         }];
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
             [findFQueue waitUntilAllOperationsAreFinished]; 
            [app endBackgroundTask];
        }); 
}

注意:如果使用过多的cpu / men / energy,你仍然可以取消...查看文档

注2:这可以写在任何地方。我把它放在OP中,但也许在VC中是一个更好的地方...... 不这么认为,但可能是

注3:阅读文档! :: https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html