IOS development: How to suspend the main thread
However, in some cases, we want the main thread to wait for the IO operation to complete-for example, after the main thread creates a folder, wait for the completion and then create a file in the folder.
The NSObject class has a method named maid mainthread: withObject: waitUntilDone that can suspend the main thread, but the selector can only contain one parameter that can be passed. In this case, the NSInvocation class is used to solve this problem.
The Code is as follows:
-(Void) createRecordDirectoryBlockingMainThread
{
NSFileManager * dfm = [NSFileManager defamanager manager];
SEL sel = @ selector (createDirectoryAtPath:
WithIntermediateDirectories:
Attributes:
Error :);
NSMethodSignature * sig = [dfm methodSignatureForSelector: sel];
// The method signature actually contains the target, selector, and type information of each parameter, but does not contain the memory address of the target and method. This information is used to accurately obtain the value of each parameter during function stack pressure.
NSInvocation * ivct = [NSInvocation invocationWithMethodSignature: sig];
[Ivct setTarget: dfm];
[Ivct setSelector: sel]; // provides the memory address of the method.
FilePathManager * fpm = [FilePathManager sharedInstance];
NSString * path = fpm. programRecordDirectoryPath;
[Ivct setArgument: & path atIndex: 2]; // the index of the parameter in the array starts from 2.
[Ivct setArgument :( void *) & BOOL_NO atIndex: 3]; // (void *) type conversion can avoid compiler warning
[Ivct setArgument :( void *) & ID_NIL atIndex: 4];
[Ivct setArgument :( void *) & VOID_NULL atIndex: 5];
[Ivct initialize mselecw.mainthread: @ selector (invoke)
WithObject: nil
WaitUntilDone: YES]; // suspends the main thread
}