I have a class with 2 methods, the first one makes an animation for a second and the second performs some task.
This class is being called from a second class to perform those two operations consecutively but I want to enforce a lock so that the second operation runs only when the first one finished.
My Question is, what is the best way to do that.
here is my code:
@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 cu开发者_运维知识库rrentRunLoop] 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
And the code that calls it:
- (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;
}
Option 1
Change operation A to be a BOOL method and return YES once completed and in your AppController
if([server operationA]) // operation A returns YES when completed so run operationB
[server operationB];
Option 2 added as per JeremyP's comment
in your delegate method (animationFinished:) for OperationA add [self operationB];
to run operationB:
at the end of your animation cycle.
精彩评论