我找不到我在当前项目中所做工作的原始来源。
我将 NSOperation 子类化并执行此操作...
在.m中添加私有属性...
@property (nonatomic) BOOL executing;
@property (nonatomic) BOOL finished;
@property (nonatomic) BOOL completed;
初始化操作...
- (id)init
{
self = [super init];
if (self) {
_executing = NO;
_finished = NO;
_completed = NO;
}
return self;
}
添加函数以返回属性...
- (BOOL)isExecuting { return self.executing; }
- (BOOL)isFinished { return self.finished; }
- (BOOL)isCompleted { return self.completed; }
- (BOOL)isConcurrent { return YES; }
在“开始”函数中(这是 operationQueue 调用的位...
- (void)start
{
if ([self isCancelled]) {
[self willChangeValueForKey:@"isFinished"];
self.finished = YES;
[self didChangeValueForKey:@"isFinished"];
return;
}
// If the operation is not canceled, begin executing the task.
[self willChangeValueForKey:@"isExecuting"];
self.executing = YES;
[self didChangeValueForKey:@"isExecuting"];
[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
}
然后在 main 中放入你的工作代码...
- (void)main
{
@try {
//this is where your loop would go with your counter and stuff
//when you want the operationQueue to be notified that the work
//is done just call...
[self completeOperation];
}
@catch (NSException *exception) {
NSLog(@"Exception! %@", exception);
[self completeOperation];
}
}
编写完成操作的代码...
- (void)completeOperation {
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
self.executing = NO;
self.finished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
就是这样。
只要你有这些,那么操作就可以工作。
您可以根据需要添加任意数量的其他函数和属性。
事实上,我实际上已经对这个类进行了子类化,因为我有一个函数可以为不同类型的对象完成所有工作(这是一个上传的东西)。我已经定义了一个函数...
- (void)uploadData
{
//subclass this method.
}
那么我在子类中只有一个自定义的“uploadData”方法。
我发现这真的很有用,因为它可以让您精细控制何时完成操作等...