Suspends the main thread in IOS.

Source: Internet
Author: User

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 }

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.