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