iOS development: How to suspend the main thread

Source: Internet
Author: User
Tags fpm

But at some point, we want the main thread to wait for the IO operation to complete--for example, after the main thread creates a folder, waits for completion, and then creates the file in the folder.

The NSObject class has a method that performSelectorOnMainThread:withObject:waitUntilDone the main thread to hang, but the selector can take at most one of the parameters that can be passed. You need to use the Nsinvocation class to solve this problem.

The code is as follows:

-(void) Createrecorddirectoryblockingmainthread

{

Nsfilemanager *DFM = [Nsfilemanager Defaultmanager];

Sel sel = @selector (createdirectoryatpath:

Withintermediatedirectories:

Attributes

Error:);

Nsmethodsignature *sig = [DFM Methodsignatureforselector:sel];

The signature of the method actually contains the target, selector, and type information for each parameter, but does not contain the memory address of the target and method. This information is to accurately get the values of each parameter when the function presses the stack

Nsinvocation *IVCT = [Nsinvocation Invocationwithmethodsignature:sig];

[Ivct SETTARGET:DFM];

[Ivct Setselector:sel]; Provide 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 at 2

[Ivct setargument: (void *) &bool_no atindex:3]; Type conversions of (void *) can avoid compiler warnings

[Ivct setargument: (void *) &id_nil atindex:4];

[Ivct setargument: (void *) &void_null atindex:5];

[Ivct Performselectoronmainthread: @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.