iOS Periodically perform a low-priority task while

2019-07-25 00:22发布

问题:

In the iOS App development process. I want to periodically perform a low priority task. And do not want this task will affect the main program of work. What is the way to achieve it?

Now I use the timer to perform periodical task, but often find the App is not smooth.

The low priority task sometime need run on the main thread, such as check pasteboard than display the content on UI.

回答1:

You will have to use Blocks(Completion handlers) for this, it's part of GCD. This will stay away from main thread.

Make a NSObject class named "backgroundClass".

in .h file

typedef void (^myBlock)(bool success, NSDictionary *dict);

@interface backgroundClass : NSObject

@property (nonatomic, strong)  myBlock completionHandler;

-(void)taskDo:(NSString *)userData block:(myBlock)compblock;

in .m file

-(void)taskDo:(NSString *)userData block:(myBlock)compblock{
  // your task here
// it will be performed in background, wont hang your UI. 
// once the task is done call "compBlock" 

compblock(True,@{@"":@""});
}

in your viewcontroller .m class

- (void)viewDidLoad {
    [super viewDidLoad];
backgroundClass *bgCall=[backgroundClass new];

 [bgCall taskDo:@"" block:^(bool success, NSDictionary *dict){
// this will be called after task done. it'll pass Dict and Success.    

dispatch_async(dispatch_get_main_queue(), ^{
 // write code here if you need to access main thread and change the UI.
// this will freeze your app a bit.
});

}];
}