getting the object passed to the NSThread selector

为君一笑 提交于 2019-12-19 04:57:20

问题


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
}

回答1:


You're specifying your selector wrong:

@selector(startTimerThread)   // we are missing ':' at the end

It should have : at the end, like so:

@selector(startTimerThread:) 

This indicates it's a selector which takes one parameter.

Then take in the parameter in your startTimerThread method:

-(void) startTimerThread:(NSNumber *)myNumber {
    // ... etc



回答2:


that will not work.. this will:

NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread:) object:[NSNumber numberWithInt:index]];


-(void) startTimerThread:(NSNumber *)thenumberhere
{


    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];
}

you 'forgot' to add the object, that you pass along with the selector as a parameter, to the method you implemented.



来源:https://stackoverflow.com/questions/5310328/getting-the-object-passed-to-the-nsthread-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!