我有一个有两个方法的类,第一个做动画的第二个,第二个执行一些任务。
这个类是从第二个类调用的,以连续执行这两个操作,但我希望强制执行一个锁,以便第二个操作只在第一个操作完成时运行。
我的问题是,做这件事的最好方法是什么。
这是我的代码:
@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;
}发布于 2011-04-19 14:50:54
选项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:。
https://stackoverflow.com/questions/5717993
复制相似问题