将对象传递给 NSThread 选择器
当我创建 NSThread 时,我向它传递了一个我希望进程知道的数字。我可以理解如何设置数字,但我不知道如何从线程选择器方法中读取数字,以便我可以将其传递给计时器。
你怎么做?
-(void) setthread
{
// 在这里将数字传递给选择器
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:[NSNumber numberWithInt:index]];/
[timerThread setThreadPriority:0.5];
[timerThread start]; //start the thread
}
// 不知道如何读取传递给该选择器的值
-(void) startTimerThread
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[[NSTimer scheduledTimerWithTimeInterval: 0.1
target: self
selector: @selector(timerTick:)
userInfo: thenumberhere
repeats: YES] retain];
[runLoop run];
[pool release];
}
- (void)timerTick:(NSTimer *)timer
{
//code
}
When I'm creating an NSThread I pass it a number that I want the process to be aware of. I can understand how to set the number but I cannot figure out how to read the number from the thread selector method so that I can then pass it to a timer.
How do you do it?
-(void) setthread
{
//passing the number to the selector here fine
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:[NSNumber numberWithInt:index]];/
[timerThread setThreadPriority:0.5];
[timerThread start]; //start the thread
}
// don't get how to read the value passed to this selector
-(void) startTimerThread
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[[NSTimer scheduledTimerWithTimeInterval: 0.1
target: self
selector: @selector(timerTick:)
userInfo: thenumberhere
repeats: YES] retain];
[runLoop run];
[pool release];
}
- (void)timerTick:(NSTimer *)timer
{
//code
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您指定的选择器是错误的:
它应该在末尾有
:
,如下所示:这表明它是一个带有一个参数的选择器。
然后在
startTimerThread
方法中获取参数:You're specifying your selector wrong:
It should have
:
at the end, like so:This indicates it's a selector which takes one parameter.
Then take in the parameter in your
startTimerThread
method:那不行..
这将:
您“忘记”将与选择器一起作为参数传递的对象添加到您实现的方法中。
that will not work..
this will:
you 'forgot' to add the object, that you pass along with the selector as a parameter, to the method you implemented.