2011-04-19 116 views
0

我有一個類有2個方法,第一個使一秒動畫,第二個執行一些任務。等待鎖定NSLock,直到tryLock成功

從第二個類中調用此類來連續執行這兩個操作,但我想強制執行鎖定,以便第二個操作僅在第一個操作完成時才運行。

我的問題是,什麼是最好的方式來做到這一點。

這裏是我的代碼:

@implementation Server 


- (id)init{ 

    if ((self = [super init])) { 
     syncLock = [[NSLock alloc] init]; 
    } 
    return self; 
} 

- (void)operationA { 
    NSLog(@"op A started"); 

    [syncLock lock]; 

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)]; 
    [view setBackgroundColor:[UIColor redColor]]; 
    [[[[UIApplication sharedApplication] delegate] window] addSubview:view]; 

    [UIView beginAnimations:@"opA" context:nil]; 
    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationDidStopSelector:@selector(animationFinished)]; 
    [UIView setAnimationDuration:1.5f]; 
    [view setFrame:CGRectMake(50, 50, 150, 150)]; 
    [UIView commitAnimations]; 

} 
- (void)animationFinished { 
    [syncLock unlock]; 
    NSLog(@"Op A finished"); 

} 

- (void)operationB { 
    if (![syncLock tryLock]) { 
     [[NSRunLoop currentRunLoop] addTimer:[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(operationB) userInfo:nil repeats:NO] forMode:NSDefaultRunLoopMode]; 
     return; 
    } 
    NSLog(@"op B started"); 

    NSLog(@"perform some task here"); 
    [syncLock unlock]; 
    NSLog(@"op B finished"); 
} 
@end 

並調用它的代碼:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

    // Override point for customization after application launch. 

    [self.window makeKeyAndVisible]; 

    Server *server = [[Server alloc] init]; 
    [server operationA]; 
    [server operationB]; 

    return YES; 
} 

回答

1

選項1

變更操作是一個布爾方法並返回YES一次完成並在您的AppController中

if([server operationA]) // operation A returns YES when completed so run operationB 
    [server operationB]; 

選項2添加爲每JeremyP的評論

在您的委託方法

(animationFinished :)用於運行a添加[self operationB];在動畫週期結束運行operationB:

+0

您也可以在委託方法(animationFinished :)內調用[self operationB]。 – 2011-04-19 14:58:05

+0

我可以同時做這兩件事,但我感興趣的是AppDelegate或調用類從不同的角度分別調用它們,OpA和OpB是鬆散耦合的。並非每次A被調用B都會被調用。 – 2011-04-19 15:36:17

+0

你的評論應該在答案中。我認爲這是正確的做法。 – JeremyP 2011-04-19 15:42:35