2012-09-05 52 views
0

問題是,如果我創建並顯示兩個警報 - 第二個將覆蓋第一個,並在它關閉後顯示第一個。所以不漂亮。NSOperaionQueue和UIAlertView

我想用NSOperationQueue創建隊列警報。您可以添加一些警報,並顯示要關閉的序列。但我不能這樣做,我會添加操作按順序執行,等待前一個。它們並行執行。

AlertOperation.h

#import <Foundation/Foundation.h> 

@interface AlertOperation : NSOperation<UIAlertViewDelegate> 

@property (nonatomic,assign) BOOL isFinishedAlert; 

- (AlertOperation *)initWithAlert:(UIAlertView *)alert; 

@end 

AlertOperation.m

#import "AlertOperation.h" 

@interface AlertOperation() 
{ 
    UIAlertView *_alert; 
} 

@end 

@implementation AlertOperation 

@synthesize isFinishedAlert  = _isFinishedAlert; 

- (AlertOperation *)initWithAlert:(UIAlertView *)alert 
{ 
    self = [super init]; 

    if (self) 
    { 
     _alert = alert; 
     _alert.delegate = self; 
     [_alert show]; 
    } 

    return self; 
} 

- (void) main 
{ 
    _isFinishedAlert = NO; 

    do { 
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
    } while (!_isFinishedAlert); 
} 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    _isFinishedAlert = YES; 
} 

- (BOOL) isConcurrent 
{ 
    return NO; 
} 
@end 

這裏運行代碼

UIAlertView *u1 = [[UIAlertView alloc] initWithTitle:@"" 
message:@"Hello i am first alert" delegate:nil 
cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

UIAlertView *u2 = [[UIAlertView alloc] initWithTitle:@"" 
message:@"Hello i am second alert" delegate:nil 
cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

NSOperation *alertOp1 = [[AlertOperation alloc] initWithAlert:u1]; 
NSOperation *alertOp2 = [[AlertOperation alloc] initWithAlert:u2]; 

alertsQueue = [[NSOperationQueue alloc] init]; 
[alertsQueue setMaxConcurrentOperationCount:1]; 

[alertsQueue addOperation:alertOp1]; 
[alertsQueue addOperation:alertOp2]; 
+0

把[_alert show]放在主 – Felix

+0

是的!謝謝@ phix23!簡單的邏輯。 – glebus

回答

0

讓你自己更容易些。創建一個可變數組。當你有新的警報顯示,然後將它們推到陣列上。每次警報結束(獲得其委託的消息),然後分派下一個警報到主隊列:

NSMutableArray *alerts; 

... end of Alert Delegate message 
if([alert count]) { 
    UIAlert *alrt = [alerts objectAtIndex:0]; 
    [alerts removeObjectAtIndex:0]; 
    dispatch_async(dispatch_get_main_queue(), ^{ [alrt show]; }); 
} 
0

我感動[_alert秀]至 - (空)的主要方法,它的工作!謝謝@ phix23的幫助!