NSOperation和NSOperationQueue在后台执行任务

时间:2015-08-21 14:37:18

标签: ios objective-c nsoperation nsoperationqueue

我想编写一个NSOperationQueue来执行另一个线程上的任务。 所以我创建了NSOperationQueue和从NSOperation派生的类。我在那里添加了一个协议来知道任务是否完成没有错误等等。但是如果我在其他类中添加一个实例并在那里设置委托,那么主线程会等待异步任务来执行代理代码。如何防止它。我希望在后台任务运行时在我的应用程序中执行某些操作。

AsyncTask.h

@protocol AsyncTaskEventsProtocol <NSObject>

-(void)OnFinishedSuccess:(NSObject *)sender information:(NSString *)inf;
-(void)OnFinishedFailed:(NSObject *)sender information:(NSString *)inf exception:(NSException *) ex;

@end

@interface AsyncOperation : NSOperation
@property id<AsyncTaskEventsProtocol> delegate;
@end

Async.m

#import "AsyncOperation.h"

@implementation AsyncOperation
@synthesize delegate;

-(void)main{
    NSException * ex;
    @try {
            NSLog([NSThread isMainThread] ? @"This is the main thread" : @"This is not the main thread");
    }
    @catch (NSException *exception) {
        ex = exception;
    }

    if(delegate != nil)
    {
        if(ex == nil){
            [delegate OnFinishedSuccess:nil information:@"Data has been sent"];
        }
        else
        {
            [delegate OnFinishedFailed:nil information:@"Data has not been sent." exception:ex];
        }
     }

}
@end

在其他创建队列的类

AsyncOperation * op = [[AsyncOperation alloc] init];
op.delegate = self;
NSOperationQueue * queue = [[NSOperationQueue alloc] init];

[queue addOperation:op]

和处理程序

-(void)OnFinishedSuccess:(NSObject *)sender information:(NSString *)inf
{
    UIAlertView * view = [[UIAlertView alloc] initWithTitle:@"Test" message:@"Message" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
                          [view show];
}

0 个答案:

没有答案