Generally, io-related operations in IOS are multi-threaded and not completed in the main thread. This is to avoid the time-consuming Io operations getting stuck in 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.
CodeAs 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]; // Memory Address of the provided 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 into mselecw.mainthread: @ selector (invoke) withobject: Nil waituntildone: Yes]; // Suspend main thread }