IOS開發:關於performSelectorXXX的延遲的使用

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
多線程

這個方法是單線程的,也就是說只有當前調用次方法的函數執行完畢後,selector方法纔會被調用。app

好比:ide


- (void)changeText:(NSString *)string函數

{spa

label.text = string;線程

NSLog(@"changeText:(NSString *)string");orm

}string


- (void)changePopoverSizeit

{ form

[self performSelector:@selector(changeText:) withObject:@"Happy aha" afterDelay:1];


NSLog(@"changePopoverSize#####end");

sleep(5);

NSLog(@"changePopoverSize-----end");

}





執行結果(注意時間):


2012-08-17 17:14:06.697 awrbv[1973:f803] changePopoverSize#####end

2012-08-17 17:14:11.698 awrbv[1973:f803] changePopoverSize-----end

2012-08-17 17:14:11.701 awrbv[1973:f803] changeText:(NSString *)string

若是要想多線程的話,能夠是使用

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg

或者

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;


代碼以下:


- (void)changeText:(NSString *)string

{

label.text = string;

NSLog(@"changeText:(NSString *)string");

}


- (void)changePopoverSize

{

[self performSelectorOnMainThread:@selector(changeText:) withObject:@"Happy aha111" waitUntilDone:YES];

NSLog(@"changePopoverSize#####end");

sleep(5);

NSLog(@"changePopoverSize-----end");

}

執行結果以下:


2012-08-17 17:19:29.618 awrbv[2024:f803] changeText:(NSString *)string

2012-08-17 17:19:29.619 awrbv[2024:f803] changePopoverSize#####end

2012-08-17 17:19:34.620 awrbv[2024:f803] changePopoverSize-----end

能夠看出,若是waitUntilDone:YES那麼等changeText執行完畢後再往下執行

若是waitUntilDone:NO的話,結果以下:


2012-08-17 17:21:12.135 awrbv[2049:f803] changePopoverSize#####end

2012-08-17 17:21:17.137 awrbv[2049:f803] changePopoverSize-----end

2012-08-17 17:21:17.139 awrbv[2049:f803] changeText:(NSString *)string

相關文章
相關標籤/搜索