threads and timers

One: Multithreading

 

1, NSThread creates a thread

 

  a, NSThread class method to create a thread

   [NSThread detachNewThreadSelector:@selector(doing) toTarget:self withObject:nil];

 

 withObject parameter The following methods are similar

 

  b, the constructor to create a thread needs to start

 

   NSThread *th=[[NSThread alloc]initWithTarget:self selector:@selector(doing) object:nil];

    

 

        [th start];

 

 c, View creation

   [self performSelectorInBackground:@selector(doing) withObject:nil];

 

 

 

 

2, Operation creates a thread

 

   a, Operation creates a thread

   

//Create an Operation queue, add to create
NSOperationQueue *queue =[[NSOperationQueue alloc]init];
    
        [queue addOperationWithBlock:^{
    
           // execute method
        }];

 

b, Operation starts multiple threads, which can set the priority of threads

NSInvocationOperation *operation1=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:@"1"];
    NSInvocationOperation *operation2=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:@"2"];
    
    
    [operationQueue addOperation:operation1];
    [operationQueue addOperation:operation2];

 

 

 

3. GCD creates threads

   

  dispatch_queue_t queue=dispatch_queue_create("baihe", nil);
    
    dispatch_async(queue, ^{
      
    });

 

 

 

Two: timer

 

See the timer operation below

 [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doing) userInfo:nil repeats:YES]; This statement may not be output and may be returned

 

Solution: // Get the current thread to prevent being returned and cannot be executed

    [[NSRunLoopcurrentRunLoop] run];

 

Generally, timing operations are not performed in the main thread, and the thread is opened to use the automatic release pool operation.

/**
     TimerInterval : Time to wait before executing. For example, if it is set to 1.0, it means that the method will be executed after 1 second.
     
     target : The object on which the method needs to be executed.
     
     selector : the method to execute
     
     repeats : whether to loop
    */
    
    @autoreleasepool {

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

        //RUNLoop management timer
// [[NSRunLoop currentRunLoop] addTimer: timer forMode: NSDefaultRunLoopMode];
        

    //Get the current thread to prevent being returned and unable to execute
    [[NSRunLoop currentRunLoop] run];
    
    
// [timer invalidate];//Stop the timer

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326973423&siteId=291194637
Recommended