简体   繁体   中英

AsyncTask using NSOperation in iOS

I implemented AsyncTask(Android) in iOS using NSOperation subclass.

-(id)initWithParam:(NSArray *)params{

if (self = [super init]) {

    paramsArray = params;
}
return self;

}

- (void)main {

// 4
@autoreleasepool {

    if (self.isCancelled)
        return;
    NSInteger result;

    result = [self doInBackground:paramsArray];

    dispatch_async(dispatch_get_main_queue(), ^{

        [self postExecute:result];
    });
}
}


- (BOOL) doInBackground: (NSArray *) parameters{

BOOL status = false;
int i;
for (i=0; i<100000; i++) {
    NSLog(@"printing i::%d",i);
}
if (i == 100000) {
    status = YES;
}

return status;
}
- (void) postExecute: (BOOL) deviceState{

if (deviceState) {
    NSLog(@"Finished");
}

}

This is the way I implemented in iOS. Any thing I missed in this implementation.

So in this way I can check isFinished, isRunning in main thread.

Please suggest me can I do like this or not?

Try using GCD:

AsyncTask.h:

#import <Foundation/Foundation.h>

@interface AsyncTask : NSObject

- (void)onPreExecute:(void (^)())mainThread doInBackground:(id (^)())backgroundThread onPostExecute:(void (^)(id result))finalMainThread;
@end

AsyncTask.m:

#import "AsyncTask.h"

@implementation AsyncTask

- (void)onPreExecute:(void (^)())mainThread doInBackground:(id (^)())backgroundThread onPostExecute:(void (^)(id result))finalMainThread
{
    dispatch_async(dispatch_get_main_queue(), ^{
        mainThread();

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
            id retval = backgroundThread();

            dispatch_async(dispatch_get_main_queue(), ^{
                finalMainThread(retval);
            });
        });
    });
}

@end

Implementation:

AsyncTask *checkUserActiveTask = [AsyncTask new];
[checkUserActiveTask onPreExecute:^
{
    NSLog(@"1. Main thread: %@", @([NSThread isMainThread]));
} doInBackground:^id
{
    NSLog(@"2. Background thread: %@", @(![NSThread isMainThread]));
    return @"Idan";
} onPostExecute:^(id result)
{
    NSLog(@"3. Main thread: %@", @([NSThread isMainThread]));
    NSLog(@"results: %@", result);
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM