IOS development: How to suspend the main thread

Source: Internet
Author: User

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

}

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.