SoFunction
Updated on 2025-04-12

Detailed explanation of the basic usage of iOS NSThread and NSOperation

NSThread is suitable for simple time-consuming tasks, and it has two ways to execute it.

- (void)oneClick{
 [NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:@"oneClick"];
}
-(void)doSomething:(NSString*) str{
 NSLog(@"%@",str);
}
- (void)twoClick{
 NSThread* myThread = [[NSThread alloc] initWithTarget:self
             selector:@selector(doSomething:)
             object:@"twoClick"];
 [myThread start];
}

NSOperation is suitable for methods that require complex thread scheduling, and then it defaults to use the main thread and does not create child threads.

- (void)threeClick{
 // 1. Create an NSInvocationOperation object NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
 // 2. Call the start method to start the operation [op start];
}
- (void)run
{
 NSLog(@"------%@", [NSThread currentThread]);
}
- (void)fourClick{
 NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
  // In the main thread  NSLog(@"1------%@", [NSThread currentThread]);
 }];
 // Add additional tasks (execute in child thread) [op addExecutionBlock:^{
  NSLog(@"2------%@", [NSThread currentThread]);
 }];
 [op addExecutionBlock:^{
  NSLog(@"3------%@", [NSThread currentThread]);
 }];
 [op addExecutionBlock:^{
  NSLog(@"4------%@", [NSThread currentThread]);
 }];
 [op start];

}

The above detailed explanation of the basic usage of iOS NSThread and NSOperation is all the content I share with you. I hope you can give you a reference and I hope you can support me more.