來看一個例子: oop
#import <Foundation/Foundation.h> spa
@interface MyTst : NSObject .net
- (void) print; orm
@end get
@implementation MyTst it
- (void) print io
{ form
NSLog(@"xxxxxxxxxx"); class
} import
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "MyTst.h"
int main(int argc, char * argv[]) {
// @autoreleasepool {
// return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
// }
MyTst *myClass = [[MyTst alloc] init];
// 1 [myClass performSelector:@selector(print) withObject:nil afterDelay:0];
//2 [myClass performSelector:@selector(print) withObject:nil];
return 0;
}
上面的代碼一、和2 會執行嗎?
答案是:2會執行,由於performSelector:@selector(print) withObject:nil至關於向runloop發送了一個啓動通知,收到這個通知後print方法會被馬上執行
而1不會被執行。-performSelector:withObject:afterDelay: 方法本質上是一個timer回調,而timer須要依靠RunLoop才能運轉,若是這是個非UI的程序且不手動起個RunLoop的話,程序應該直接就結束了吧,就算afterDelay:0 也沒用。若是要想執行得 [[NSRunLoop currentRunLoop] run];才行。