#import "Person.h"
@implementation Person
- (void)testLog {
[self performSelector:@selector(logd) withObject:nil afterDelay:0];//1
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"c");
});//2
[self performSelector:@selector(logb)];//3
NSLog(@"a");//4
}
- (void)logd {
NSLog(@"d");
}
- (void)logb {
NSLog(@"b");
}
@end
上面這段代碼在OS命令行程序和iOS程序中運(yùn)行結(jié)果完全不同在iOS程序中運(yùn)行結(jié)果的原理
- performSelector:@selector(logb)
知識(shí)點(diǎn):告訴線程直接調(diào)用方法 - -(void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
知識(shí)點(diǎn):這個(gè)方法是單線程的吨艇,也就是說(shuō)只有當(dāng)前調(diào)用此方法的函數(shù)執(zhí)行完畢后躬它,selector方法才會(huì)被調(diào)用。 - dispatch_after能讓我們添加進(jìn)隊(duì)列的任務(wù)延時(shí)執(zhí)行秸应,該函數(shù)并不是在指定時(shí)間后執(zhí)行處理虑凛,而只是在指定時(shí)間追加處理到dispatch_queue
程序執(zhí)行到//1的時(shí)候碑宴,系統(tǒng)會(huì)等待testlog全部執(zhí)行完再延時(shí)0s執(zhí)行l(wèi)ogd方法;
執(zhí)行到//2的時(shí)候软啼,告訴主隊(duì)列0s后添加logc任務(wù)到主隊(duì)列;
執(zhí)行到//3的時(shí)候,主線程直接執(zhí)行l(wèi)ogb方法延柠,打印b祸挪;
執(zhí)行到//4的時(shí)候,主線程直接打印a贞间;
打印完a贿条,將需要延時(shí)加入進(jìn)隊(duì)列的方法加進(jìn)主隊(duì)列,而(void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay需要等待當(dāng)前函數(shù)testlog執(zhí)行完才能調(diào)用增热,所以先加進(jìn)隊(duì)列的是logc整以,打印c;
打印完c,testlog函數(shù)全部執(zhí)行完畢,執(zhí)行l(wèi)ogd方法峻仇,打印d公黑。