Ios:. Nsrunloop Understand again

Source: Internet
Author: User

We will often see this code:

1
2
3
4
5
6
7
8
9
10
-(Ibaction) Start: (ID) sender
{
pagestillloading = YES;
[Nsthread detachnewthreadselector: @selector (loadpageinbackground:) totarget:self Withobject:nil];
[Progress Sethidden:no];
while (pagestillloading) {
[Nsrunloop Currentrunloop] runmode:nsdefaultrunloopmode beforedate: [NSDate distantfuture]];
}
[Progress Sethidden:yes];
}

This code is amazing because he will "pause" the code, and the program will not run because there is a while loop. After [progress Sethidden:no] execution, the whole function wants to suspend the same as stop in the loop, and so loadpageinbackground inside the operation is completed before let [Progress Sethidden:yes] run. This is an introduction, and the logic is clear. If you don't, you'll need to call [progress Sethidden:yes] in the loadpageinbackground where the load is done, and the code is not compact and error prone.

1.NSRunLoop is the processing mode of the message mechanism

Nsrunloop's role is to have things done when the current Nsrunloop thread works, nothing to do to make the current Nsrunloop thread hibernate


2.nstimer is added to the current nsrunloop by default, or you can manually make the additions to your new Nsrunloop


[Nstimer SchduledTimerWithTimeInterval:target:selector:userInfo:repeats];

This method is added by default to the current Nsrunloop


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

Nstimer *timer = [[Nstimer alloc] initwithfiredate: ...];

Create timer [[Nsrunloop Currentrunloop] Addtimer:timer formode:nsrunloopcommonmodes];

Pay attention to the release of the timer


3.NSRunLoop is always in the loop detection, from thread start to thread end, detect InputSource (such as click, double-click, etc.) synchronization events, detect TimeSource synchronization events, detect the input source will perform processing functions, first will produce a notice, Corefunction adds Runloop observers to the thread to listen for the event, which is intended to be handled when the event occurs.


4.runloopmode is a collection that includes monitoring: event sources, timers, and Runloop observers to notify

Patterns include:

Default mode: Almost including all input sources (except Nsconnection) Nsdefaultrunloopmode mode

Mode mode: Handling modal panels

Connection mode: Handle Nsconnection event, belong to system inside, user basically don't need

Event Tracking Mode: component Drag input source Uitrackingrunloopmodes do not handle timed events

Common modes Mode: Nsrunloopcommonmodes This is a configurable set of common patterns. Associating the input sources with the schema also associates the input sources with other schemas in the group.


Each time you run a run loop, you specify the operating mode (explicit or implicit) of the run loop. When the corresponding pattern is passed to the run loop, only the input sources that corresponds to the pattern is monitored and the run loop is allowed to handle the event (similarly, only the observers corresponding to the pattern is notified)




Cases:

1. At the same time as the timer and table, when dragging the table, runloop into the uitrackingrunloopmodes mode, does not handle timed events, at this time timer can not handle, So now add the timer to Nsrunloopcommonmodes mode (AddTimer formode)

2. When scroll a page to loosen, at this time connection will not receive the message, because scroll when runloop for uitrackingrunloopmodes mode, do not receive input source, at this time to modify the connection mode

[Scheduleinrunloop:[nsrunloop Currentrunloop]formode:nsrunloopcommonmodes];


5. About-(BOOL) RunMode: (NSString *) mode beforedate: (NSDate *) Date; method

Specifies the Runloop mode to process the input source, the first input source or date end exit.

Pauses the currently processed process, instead of processing other input sources, and when date is set to [NSDate Distantfuture] (in the future, it will not arrive at all), never quits the process of processing a paused current process unless the other input sources are processed.


6.while (A) {

[[Nsrunloop Currentrunloop] Runmode:nsdefaultrunloopmode beforedate:[nsdate Distantfuture]];

}

When the current A is yes, the current runloop will always receive processing other input sources, the current process does not continue processing, a is no, the current process continues


7.perform selector is serialized in thread, easing many of the synchronization problems that are generated by running multiple methods in the same thread. Perform selector source is automatically removed from the run loop after the selector is finished running.

When perform selector in non main thread, there must be an active run loop in its thread. For the thread you created yourself, the perform selector can only be executed if your code explicitly runs a run loop. The run loop processes all queued perform selector While the loop is running, not only one perform selector in a loop loop.


8.performSelector the execution principle of memory management is such execution [self performselector: @selector (method1:) WithObject:self.tableLayer Afterdelay : 3]; , the system will tablelayer reference count plus 1, the execution of this method, will also tablelayer reference count minus 1, due to the delay Tablelayer reference count has not been reduced to 0, also led to the switch scene Dealloc method is not called, A memory leak has occurred.

Use the following function:

[NSObject Cancelpreviousperformrequestswithtarget:self]

Of course you can do it one at a way:

[NSObject cancelpreviousperformrequestswithtarget:self selector: @selector (method1:) Object:nil]

After adding this, the Dealloc method was successfully executed.


Inside the Touchbegan.

[Self performselector: @selector (longpressmethod:) Withobject:nil Afterdelay:longpresstime]

Then make a judgment in end or cancel if the time is not long enough to call:

[NSObject cancelpreviousperformrequestswithtarget:self selector: @selector (longpressmethod:) Object:nil]

Cancel the method in began


Here's a summary of what I saw in Cocoachina.

Several ways to implement threads:
1. Operation Objects//Nsoperation and related sub-classes
2. * * *//Dispatch_async and other related functions
3. Idle-time Notifications//Nsnotificationqueue, Low priority
3. Asynchronous functions//asynchronous function
4. Timers//Nstimer
5. Separate processes//no use

Cost of Thread creation:
Kernel data Structures about 1KB
Stack space 512KB (secondary threads)
1MB (IOS main thread)
Creation time about microseconds

Run Loop and thread relationships:
1. The run loop of the main thread is initiated by default and is used to receive various input sources
2. For the second thread, the run loop is not started by default, and if you need more thread interaction you can configure and start manually, if the thread executes a long determined task.

The Run loop is used in any case:
A. Communicating//not understanding with ports or input sources and other threads
B. Using timers//In a thread does not respond if the event does not start run Loop,timer
C. Use of Performselector in cocoa applications ... Method//should be performselector ... This method starts a thread and starts the run loop.
D. Let the thread perform a recurring task//If the run loop is not started, the thread may be released by the system after running

Note: Timer creation and release must be in the same thread.
[[Nsrunloop Currentrunloop] Addtimer:timer formode:nsrunloopcommonmodes]; This method retain the reference count of the timer object.


/////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////

The following is a Cfrunloop demo to help understand its use:

/!!! If you do not have the following currentloop then the timer in the Initplayer method is not executed and the Playerthread is finished.
-(void) Playerthread: (ID) unused
{
Currentloop = Cfrunloopgetcurrent ()//Runloop reference for child threads

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];//create an automatic free pool for child threads

[Self initplayer];

Cfrunlooprun ();

[Pool release];
}

-(void) Initplayer
{
Here you can initialize a work class, such as sound or video playback.
[Nstimer scheduledtimerwithtimeinterval:3.0 Target:self
Selector: @selector (checkstate:) Userinfo:nil Repeats:yes];
}

-(void) CheckState: (nstimer*) Timer
{
You need to exit the custom thread.
if ()
//{
Releasing resources inside a child thread
Code to release the resource ....
/* End Child thread task Cfrunloopstop,this function forces RL to stop running and
Return control to the function that called Cfrunlooprun or Cfrunloopruninmode
For the current run loop activation. If the run loop is nested with a callout
From one activation starting another activation running, only the innermost
Activation is exited.*/
Cfrunloopstop (Currentloop);
//}

for (int i = 0; i < i++)
{
NSLog (@ "%d", I);
}

Cfrunloopstop will end the current timer, and if Runloop doesn't end, the timer will execute repeatedly.
Cfrunloopstop (Currentloop);

}

-(void) Click: (ID) sender{
Nsthread *thread = [[Nsthread alloc] initwithtarget:self selector: @selector (playerthread:) Object:nil];

Open the thread, if the use of nsoperation, only need to join the nsoperationqueue inside, the queue itself will be at the right time to execute the thread, without the programmer to control themselves.
[Thread start];

}

-(void) viewdidload
{
[Super Viewdidload];

[Self.view Setbackgroundcolor:[uicolor Whitecolor]];

UIButton *button = [[UIButton alloc] Initwithframe:cgrectmake (10, 10, 100, 50)];
[Button Setbackgroundcolor:[uicolor Bluecolor]];
[Button settitle:@ "abc" forstate:uicontrolstatenormal];
[Button Settitlecolor:[uicolor Whitecolor] forstate:uicontrolstatenormal];
[Button Settitlecolor:[uicolor Redcolor] forstate:uicontrolstatehighlighted];
[Button Setbackgroundcolor:[uicolor Bluecolor]];
[Button addtarget:self Action: @selector (click:) Forcontrolevents:uicontroleventtouchdown];
[Self.view Addsubview:button];
[Button release];

}

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.