Cocoa Touch (vi): app operating mechanism Nsrunloop, KVC, KVO, Notification, ARC

Source: Internet
Author: User

Event Loop Nsrunloop

1. Run Loop concept

The Nsrunloop class encapsulates the process by which a thread enters the event loop, and a Runloop instance represents the event loop of a thread.

There are two types of events that are received by the thread in the event loop: input source and timer source. Thread invoke convenience function [Nstimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:] While creating a Nstimer instance, The default mode defaults to register a timer source in the current thread 's run loop, and adds the newly created timer to the run loop as the observer for the event.

However, each thread does not immediately add it to the run loop when creating the timer, only calls [Nstimer timerWithTimeInterval:target:selector:userInfo:repeats:], or you can call [[Nstimer alloc] InitWithFireDate:interval:target:selector:userInfo:repeats:], the two methods are equivalent. Then use [Nsrunloop Currentrunloop] to get the corresponding event loop object, and then call the [Runloop Addtimer:formode:] method, then register a timed event, before the timer expires, the current thread will not directly terminate, Instead, it is in the state of waiting for the event source.

2. Run loop mode type

Threads running under different run loop mode are running differently, and threads only check the source of the event at the current mode. For example:

-(void) viewdidload{    [Super Viewdidload];     * Timer = [Nstimer scheduledtimerwithtimeinterval:1                                              target:self                                            selector: @selector ( Printmessage:)                                            userinfo:nil                                             repeats:yes];}

this time if we scroll a scrollview on the interface, then we will find that the console will not have any output until the scrolling is stopped, as if ScrollView paused the timer while scrolling, which is actually the run Loop is in a different mode.

When adding a nstimer to the current Runloop, you must also set the event source's run loop mode, and when ScrollView scrolls, The current Mainrunloop object is in Uitrackingrunloopmode mode, and in this mode the Nsdefaultrunloopmode message is not processed (because the thread is in the run loop mode and the event source Loop mode does not match), we need to change the run loop mode between the two if we want to accept other Runloop messages while the ScrollView is rolling.

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

3, Timer Nstimer

Some of the usage of the timer has been explained above, that is, you can register a timer event source with an instance of Nstimer in a Nsrunloop instance and register the timer instance as the observer for the event.

A timer and timing event is bound, using the fire method in the timer and the Invalidate method to control the life cycle of a timer, no repetition of the timer in the fire immediately after the invalidate, for the repeated timer, Manual invalidate is required. Or you can change the date a timer is triggered, and if the trigger date is distant past, it will be triggered immediately. As

Turn off the timer
[MyTimer setfiredate:[nsdate distantfuture];
Turn on timer
[MyTimer setfiredate:[nsdate Distantpast];

When a Nstimer instance that is a listener is triggered, the thread invokes the Nstimer instance's action callback method, and there is a way to easily pass multiple arguments, using an instance of the calling class Nsinvocation class.

#import<Foundation/Foundation.h>#import "MyClass.h"intMain (intargcConst Char*argv[]) {@autoreleasepool {MyClass*myclass =[[MyClass alloc] init]; NSString*mystring =@"My String"; //Normal CallNSString *normalinvokestring =[MyClass appendmystring:mystring]; NSLog (@"The normal invoke string is:%@", normalinvokestring); //Nsinvocation CallSEL Myselector =@selector (appendmystring:); Nsmethodsignature* sig = [[MyClassclass] Instancemethodsignatureforselector:myselector]; Nsinvocation* Myinvocation =[Nsinvocation Invocationwithmethodsignature:sig];    [Myinvocation Settarget:myclass];        [Myinvocation Setselector:myselector]; [Myinvocation setargument:&mystring Atindex:2]; NSString* result =Nil;        [Myinvocation retainarguments];    [Myinvocation invoke]; [Myinvocation Getreturnvalue:&result]; NSLog (@"The nsinvocation invoke string is:%@", result); return 0;}
}

The first two parameters are hidden parameters self and _cmd, corresponding to target and selector, so the custom parameter starts at index 2.

4. Date Object NSDate, NSDateFormatter

An instance of NSDate represents a date in which a thread can convert NSDate objects and NSString objects with the help of an instance of NSDateFormatter.

//The Date method returns the current time (now)NSDate *date =[NSDate Date]; //now:11:12:40//date:11:12:50Date = [NSDate Datewithtimeintervalsincenow:Ten];//returns the time 10 seconds after the current time//starting from 1970-1-1 00:00:00Date = [NSDate dateWithTimeIntervalSince1970:Ten];//returns the time of 1970-1-1 00:00:00 time 10 seconds//randomly returns a relatively distant future time.Date =[NSDate distantfuture]; //randomly returns a relatively distant past time.Date =[NSDate Distantpast]; //returns the number of milliseconds that have passed since 1970-1-1Nstimeinterval interval =[Date timeIntervalSince1970]; //compare with other timesNSDate *date2 =[NSDate Date]; //back to the earlier time[Date Earlierdate:date2]; //back to the time of the comparison later[Date Laterdate:date2]; //get a two time difference[Date1 timeintervalsincedate date2]; NSDate*date =[NSDate Date]; //2015-04-07 11:14:45NSDateFormatter *formatter =[[NSDateFormatter alloc] init]; //hh is 24 binary, HH is 12 binaryFormatter.dateformat =@"YYYY-MM-DD HH:mm:ss"; //Formatter.locale = [[[Nslocale alloc] initwithlocaleidentifier:@ "ZH_CN"] autorelease]; NSString *string=[Formatter stringfromdate:date]; NSDate *date2 = [Formatter datefromstring:@"2016-03-09 13:14:56"];

KV Monitoring Mechanism

KVC key value code & KVO Key-value monitoring

In what scenario do you need KVC? The simplest scenario, if a control's properties are declared as @property (nonatomic,readonly) read-only, then the property can only be modified by KVC. For example, when we need to replace the original Tabbar in Uitabbarcontroller with a custom tabbar. What scenario requires KVO? The Cocoa development Framework has a built-in notification mechanism that enables notification of each observer after data changes, such as when a data model is changed by a controller, notifying other controllers.

Now let's do something else and write it in a few days. Also write the arc issues related to block in a few days, such as the following

@property (nonatomic, ReadWrite, copy) Completionblock Completionblock;

__weak typeof (self) weakself = self;
Self.completionblock = ^ {
if (weakself.success) {
Weakself.success (Weakself.responsedata);
}
};

Cocoa Touch (vi): app operating mechanism Nsrunloop, KVC, KVO, Notification, ARC

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.