等待锁定的NSLock,直到tryLock成功

时间:2011-04-19 14:28:37

标签: objective-c synchronization nslock

我有一个有2个方法的类,第一个用于制作动画一秒钟,第二个用于执行某项任务。

从第二个类调用此类以连续执行这两个操作但我想强制执行锁定,以便第二个操作仅在第一个操作完成时运行。

我的问题是,最好的方法是什么。

这是我的代码:

@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 个答案:

答案 0 :(得分:1)

选项1

将操作A更改为BOOL方法,并在完成后在AppController中返回YES

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

选项2 根据JeremyP的评论添加

在您的委托方法(animationFinished :)中,对于OperationA,在动画周期结束时添加[self operationB];以运行operationB: