IOS development-guide to developing nsunloop

Source: Internet
Author: User

First, a simple Demo

We often see this Code:

-(IBAction) start :( id) sender

{

PageStillLoading = YES;

[NSThread detachNewThreadSelector: @ selector (loadPageInBackground :) toTarget: self withObject: nil];

[Progress setHidden: NO];

While (pageStillLoading ){

[Nsunloop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture];

}

[Progress setHidden: YES];

}
Copying the code is amazing because it will "pause" the code and the program running will not be affected by a while loop. After [progress setHidden: NO] is executed, the entire function is paused and stops in the loop. After the operations in loadPageInBackground are completed, the [progress setHidden: YES] can be run. This is a brief introduction and the logic is clear. If you do not do this, you need to call [progress setHidden: YES] In the loadPageInBackground to indicate that the load is complete. It seems that the Code is not compact and error-prone.
[IGoogle has the saying that the main thread of the application framework has encapsulated the call to the nsunloop runMode: beforeDate:; it and the while LOOP constitute a message pump that continuously obtains and processes messages; it may be strange to everyone that since the main thread has encapsulated the call to the nsunloop, why can we call it again here? This is the difference between it and Windows message loop, and it can be nested calls. when the while + nsunloop is called again, the program does not stop execution, and the program continuously extracts or processes messages. this is the same as the nested call of Active Scheduler in Symbian to achieve synchronization.]

 

 

1. nsunloop is the message processing mode.

The purpose of the nsunloop is to make the current nsunloop thread work when something is done, and there is no thing to do to sleep the current nsunloop thread

 


2. nstloop is added to the current nsunloop by default. You can also manually add the nstloop to the new nsunloop.

 


[NSTimer schduledTimerWithTimeInterval: target: selector: userInfo: repeats];

This method is added to the current nsunloop by default.

 


NSTimer * timer = [NSTimer timerWithTimeInterval: invocation: repeates:];

NSTimer * timer = [[NSTimer alloc] initWithFireDate:...];


Create timer [[[nsunloop currentRunLoop] addTimer: timer forMode: nsunloopcommonmodes];

Note the release of timer

 


3. nsunloop is a loop detection, from thread start to thread end, detection of inputsource (such as click, double-click and other operations) Synchronization events, detection of timesource synchronization events, it is detected that the input source will execute the processing function, and a notification will be generated first. corefunction adds runloop observers to the thread to listen for the event, which is intended to be processed when the event occurs.

 


4. runloopmode is a set of listeners, including event sources, timers, and runloop observers to be notified.

Modes include:

Default Mode: includes almost all input sources (except NSConnection) NSDefaultRunLoopMode Mode


Mode: Process modal panels

Connection Mode: Processes NSConnection events, which are internal to the system and are rarely used by users.

Event tracking mode: If a component is dragged to the input source UITrackingRunLoopModes, scheduled events are not processed.

Common modes mode: nsunloopcommonmodes is a set of configurable common modes. If you associate input sources with this mode, the input sources is also associated with other modes in this group.

 

 

Each time you run a run loop, you specify (explicitly or implicitly) the run mode of the run loop. When the corresponding mode is passed to the run loop, only the input sources corresponding to the mode are monitored and allow the run loop to process the event (similar to this, only the observers corresponding to this mode will be notified)

 

 

 

 


Example:

1 ). when timer and table are executed simultaneously, when dragging a table, runloop enters UITrackingRunLoopModes mode and does not process scheduled events. At this time, timer cannot process the tasks, so add the timer to the nsunloopcommonmodes mode (addTimer forMode)

2). When scroll is released on a page, the connection will not receive the message. Because the runloop in scroll is in UITrackingRunLoopModes mode and does not receive the input source, you need to modify the connection mode.

[ScheduleInRunLoop: [nsunloop currentRunLoop] forMode: nsunloopcommonmodes];

 


5. About-(BOOL) runMode :( NSString *) mode beforeDate :( NSDate *) date; Method

Specify the runloop mode to process the input source. The first input source or date ends and exits.

Pause the current processing process and then process other input sources. When date is set to [NSDate distantFuture] (in the future, it will not be reached), unless the processing of other input sources ends, otherwise, the process of processing the pause will never exit.

 


6. while (){

[[Nsunloop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture];


}

When A is YES, the current runloop will always receive and process other input sources. The current process does not continue to process, the output is A is NO, and the current process continues

 


7. The perform selector is serialized and executed in the thread, which mitigates synchronization problems caused by running multiple methods in the same thread. The perform selector source is automatically removed from the run loop after the selector is run.

When the perform selector is not in the main thread, the thread must have an active run loop. For a self-created thread, the perform selector can be executed only after your Code explicitly runs a run loop. Run loop processes all queued perform selectors while the loop is running, instead of processing only one perform selector during a loop.

 


8. performSelector the execution principle of memory management is as follows: [self executor mselector: @ selector (method1 :) withObject: self. tableLayer afterDelay: 3];, the system adds the reference count of tableLayer to 1. After this method is executed, the reference count of tableLayer is reduced by 1, due to the delay, the reference count of tableLayer is not reduced to 0, which leads to the failure to call the dealloc method in the switching scenario and Memory leakage.

Use the following functions:

[NSObject cancelPreviousPerformRequestsWithTarget: self]

Of course, you can also use it one by one:

[NSObject cancelPreviousPerformRequestsWithTarget: self selector: @ selector (method1 :) object: nil]

After adding this, the dealloc method is successfully executed.

 


In touchBegan

[Self defined mselector: @ selector (longPressMethod :) withObject: nil afterDelay: longPressTime]

Then make a judgment in the end or cancel. If the time is not long enough, call:

[NSObject cancelPreviousPerformRequestsWithTarget: self selector: @ selector (longPressMethod :) object: nil]

Cancel the method in began

 


* ********************************** The following is my A summary is reproduced.

Several methods of thread implementation:
1. Operation Objects // NSOperation and related subclasses
2. ***** // related functions such as dispatch_async
3. Idle-time configurations // NSNotificationQueue, with a low priority
3. Asynchronous functions // Asynchronous Function
4. Timers // NSTimer
5. Separate processes // never used

Thread creation cost:
Kernel data structures about 1 KB
Stack space 512KB (secondary threads)
1 MB (iOS main thread)
Creation time About 90 microseconds

Relationship Between Run Loop and thread:
1. The run loop of the main thread is started by default and is used to receive various input sources.
2. for the second thread, run loop is not started by default. If you need more thread interactions, You can manually configure and start it, if the thread executes a task that has been determined for a long time, it is not required.

When to use the Run Loop:
A. Use ports or input sources to communicate with other threads // unknown
B. use timers in the thread. // If run loop is not started, the timer event will not respond.
C. Use the performSelector... method in the Cocoa application // It should be the performSelector... this method will start a thread and start the run loop.
D. Let the thread execute a periodic task // If the run loop is not started, the thread may be released by the system after it is run.

Note: timer must be created and released in the same thread.
[[Nsunloop currentRunLoop] addTimer: timer forMode: nsunloopcommonmodes]; this method will retain the reference count of the timer object.


 

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.