Ale*_*lex 2 iphone xcode objective-c method-call ios
新手obj-c问题.我正在写一个简单的iPad演示文稿而不是Appstore.我的任务是实现一个接一个地执行的几个方法,它们之间几乎没有暂停.主要结构如下:
我从-viewDidLoad调用的第一个方法:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(firstCountStarts) userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)
一切都很好,方法在视图加载后2秒开始.从method1里面我尝试以相同的方式调用方法2,但它开始与method1同时执行.同样的方法触发了method3(从method2调用)以及它们之后根本没有执行的所有方法.我试图将所有这些方法放在-ViewDidLoad中,并用延迟来调用它们:
[self method1];
[self performSelector:@selector(method2) withObject:nil afterDelay:2];
[self performSelector:@selector(method3) withObject:nil afterDelay:4];
etc...
Run Code Online (Sandbox Code Playgroud)
但是在method2调用所有方法之后没有执行.如果我理解线程中的问题.我是否需要使用GCD在不同的队列中执行方法?或者可能是其他问题?
谢谢,同事们!
You could add these to an NSOperation queue...
NSOperationQueue *queue = [NSOperationQueue new];
queue.maxConcurrentOperationCount = 1;
[queue addOperationWithBlock:^{
[self method1];
}];
[queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:2.0];
[self method2];
}];
[queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:2.0];
[self method3];
}];
...
Run Code Online (Sandbox Code Playgroud)
This will then run each one only after the previous one has finished and put the 2 second delay in for you.
Careful about using this to do an UI stuff though. This will run in a Background thread so you may need to deal with that.
Maybe this might work better you could do it by subclassing NSOperation but that's a lot of work for not much benefit.
Run this from where ever you want, I suggest putting all this into a function called setUpQueue or something.
Then from viewWillAppear or viewDidLoad or somewhere else, on a button press, etc... do...
[self setUpQueue];
Run Code Online (Sandbox Code Playgroud)
All you have to do is add stuff to the queue, the queue will then manage itself.
| 归档时间: |
|
| 查看次数: |
2290 次 |
| 最近记录: |