最近做一個項目,之前的使用者登入是同步的,點擊登入後,在登入結果還沒有返回之前所有的介面都不能操作,使用者體驗非常不好。所以使用NSOperationQueue以非同步方式處理了。
///////////////////////////.h
#import <Foundation/Foundation.h>
@interface MyTask : NSOperation {
id _target;
SEL _action;
}
- (id)initWithTargetAndAction:(id)theTarget action:(SEL)theAction;
@end
///////////////////////////.m檔案
- (id)initWithTargetAndAction:(id)theTarget action:(SEL)theAction {
self = [super init];
if (self) {
_action = theAction;
_target = theTarget;
}
return self;
}
- (void)main {
//發送請求命令
}
- (void)recvData:(id)data {
[_target performSelectorOnMainThread:_action withObject:nil waitUntilDone:NO];
}
// 調用地方LoginVIew.m
- (void)sendReq {
[self startAnima];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
MyTask *task = [[MyTask alloc] initWithTargetAndAction:self action:@selector(didFinish:)];
[queue addOperation:task];
}
-(void)didFinishIn:(id)data {
[self stopAnima];
} 本執行個體主要處理重新整理進度條的顯示和隱藏的處理,同時也是登入按鈕的非同步(之前不採用非同步話,點擊按鈕後就假死狀態)。 本主要使用NSOperationQueue實現非同步處理:開始的時候建立target和action相關動作。由main函數啟動了一個子線程,相關處理在子線程中完成. 接收完成調用recvData函數。通過recvData函數通知到上層。從而實現非同步處理。