NSOperation GUNStep源码
NSInvocationOperation GUNStep源码
NSOperationQueue GUNStep源码
NSInvocationOperation只是对NSOperation的简单封装,专注于操作
两种方式初始化,但都是把要做的操作封装成 NSInvocation
对象
- (id) initWithInvocation: (NSInvocation *)inv
{
if (((self = [super init])) != nil)
{
[inv retainArguments];
_invocation = [inv retain];
}
return self;
}
- (id) initWithTarget: (id)target selector: (SEL)aSelector object: (id)arg
{
NSMethodSignature *methodSignature;
NSInvocation *inv;
methodSignature = [target methodSignatureForSelector: aSelector];
inv = [NSInvocation invocationWithMethodSignature: methodSignature];
[inv setTarget: target];
[inv setSelector: aSelector];
if ([methodSignature numberOfArguments] > 2)
[inv setArgument: &arg atIndex: 2];
return [self initWithInvocation: inv];
}
main
方法
- (void) main
{
if (![self isCancelled])
{
NS_DURING
[_invocation invoke]; // 简单的执行了 _invocation 封装的方法
NS_HANDLER
_exception = [localException copy];
NS_ENDHANDLER
}
}
操作返回值
- (id) result
{
id result = nil;
if (![self isFinished]) // 如果还没执行完
{
return nil;
}
if (nil != _exception) // 如果执行操作的时候有异常
{
[_exception raise];
}
else if ([self isCancelled]) // 如果任务取消了,就抛出异常
{
[NSException raise: (id)NSInvocationOperationCancelledException
format: @"*** %s: operation was cancelled", __PRETTY_FUNCTION__];
}
else // 通过 _invocation 的执行结果返回值
{
const char *returnType = [[_invocation methodSignature] methodReturnType];
if (0 == strncmp(@encode(void),
GSSkipTypeQualifierAndLayoutInfo(returnType), 1))
{
[NSException raise: (id)NSInvocationOperationVoidResultException
format: @"*** %s: void result", __PRETTY_FUNCTION__];
}
else if (0 == strncmp(@encode(id),
GSSkipTypeQualifierAndLayoutInfo(returnType), 1))
{
[_invocation getReturnValue: &result];
}
else
{
unsigned char *buffer = malloc([[_invocation methodSignature]
methodReturnLength]);
[_invocation getReturnValue: buffer];
result = [NSValue valueWithBytes: buffer objCType: returnType];
}
}
return result;
}
总结: NSInvocationOperation是对NSOperation的简单封装, 持有了一个NSInvocation
对面,在main
方法里调用.
GUNStep里没有 NSBlockOperation的代码, 不能粘出来学习了,哎,忧伤
网友评论