0

我有一个有 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;
}
4

1 回答 1

2

选项1

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

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

根据 JeremyP 的评论添加了选项 2

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

于 2011-04-19T14:50:54.873 回答