Running NSTimer in a thread

I am trying to run NSTimer in a stream using the iPhone SDK 3.0. I think I'm doing everything right (new runloop, etc.). If I call [timer invalidate] on viewDidDissappear, although I get this error:

bool _WebTryThreadLock (bool), 0x3986d60: tried to get a web lock from a thread other than the main thread or web thread. This may be the result of calling UIKit from the secondary stream. Failure now ... Program signal: "EXC_BAD_ACCESS".

Here is my code:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [activityIndicator startAnimating];
    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil]; //Create a new thread
    [timerThread start]; //start the thread
}

-(void)timerStart
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
    //Fire timer every second to updated countdown and date/time
    timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];
    [runLoop run];
    [pool release];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [timer invalidate];
}

When I delete a line, an invalid timer, everything works fine. Shouldn't I invalidate this, or am I making some other mistake?

thank

+3
source share
3

[timer performSelector:@selector(invalidate) onThread:timerThread withObject:nil waitUntilDone:NO];

. timerThread ivar .

+7
    - (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) userInfo:nil repeats:TRUE];
    [timerThread start]; 
    }

    -(void)timerStart
    {
   @autoreleasePool{
    NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
    [NSTimer scheduleTimerWithInterval:0.1 target:self selector:@selector(methodName:) userInfo:nil repeat:YES];
    [TimerRunLoop run];
    }

    - (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    }
+2

I think you did some UI work in " method".

 timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];

From the log, it seems you made the user interface updated by working with it in the Timer thread in the "method".

you can use the block to send work on the main thread or performSeletorOnMainThreadto execute the "method"

0
source

Source: https://habr.com/ru/post/1731418/


All Articles