与NSInvocation的主线程执行选择 [英] Performing selectors on main thread with NSInvocation
问题描述
我想在主线程(原因UIKit的对象不是线程安全的)执行动画,但是prepare它在一些单独的线程。我有(baAnimation - 是CABasicAnimation分配和放大器;前inited):
I want to perform animation on main thread (cause UIKit objects are not thread-safe), but prepare it in some separate thread. I have (baAnimation - is CABasicAnimation allocated & inited before):
SEL animationSelector = @selector(addAnimation:forKey:);
NSString *keyString = @"someViewAnimation";
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[workView.layer methodSignatureForSelector:animationSelector]];
[inv setTarget:workView.layer];
[inv setSelector:animationSelector];
[inv setArgument:baAnimation atIndex:2];
[inv setArgument:keyString atIndex:3];
[inv performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO];
我得到:
***
+ NSCFString长]:无法识别的选择发送到类0x1fb36a0
***
+[NSCFString length]: unrecognized selector sent to class 0x1fb36a0
电话:
> #0 0x020984e6 in objc_exception_throw
> #1 0x01f7e8fb in +[NSObject doesNotRecognizeSelector:]
> #2 0x01f15676 in ___forwarding___
> #3 0x01ef16c2 in __forwarding_prep_0___
> #4 0x01bb3c21 in -[CALayer addAnimation:forKey:]
> #5 0x01ef172d in __invoking___
> #6 0x01ef1618 in -[NSInvocation invoke]
但 [workView.layer addAnimation:baAnimation forKey:@someViewAnimation];
工作正常。我在做什么错了?
But [workView.layer addAnimation:baAnimation forKey:@"someViewAnimation"];
works fine. What am I doing wrong?
推荐答案
在除了[INV retainArguments](由克里斯·苏特尔提到的),你还需要传递的参数作为指针指向底层的内存。援引API:
In addition to [inv retainArguments] (as mentioned by Chris Suter) you also need to pass the arguments as pointers to the underlying memory. Citing the API:
当参数值是一个对象,传递一个指针变量(或存储器),从该物体应该被复制:
"When the argument value is an object, pass a pointer to the variable (or memory) from which the object should be copied:
NSArray *anArray;
[invocation setArgument:&anArray atIndex:3];
这篇关于与NSInvocation的主线程执行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!