我想在启动它后2秒钟运行一段代码。
我认为NSTimer可以做到这一点,但无法理解。
答案 0 :(得分:19)
可以使用NSTimer,但另一种选择是使用performSelector:withObject:afterDelay:它基本上就像稍后发生的方法调用(消息发送)。
此示例将在延迟后发送doStuff:消息:
[self performSelector:@selector(doStuff:) withObject:self afterDelay:2];
导致此方法在2.0秒后被调用:
-(void)doStuff:(id)sender
{
/// do something
}
答案 1 :(得分:11)
以下将满足您的需求:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 2
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:NO];
然后委托功能:
-(void)handleTimer: (NSTimer *) timer
{
//code
}
答案 2 :(得分:8)
您还可以使用一些方便的代码:
NSObject的+ PerformBlock.h
@interface NSObject (PerformBlock)
- (void)performBlock:(void(^)(void))block waitUntilDone:(BOOL)wait;
- (void)performBlock:(void(^)(void))block afterDelay:(NSTimeInterval)delay;
- (void)performBlock:(void(^)(void))block repeatCount:(NSUInteger)repeatCount timeInteval:(NSTimeInterval)timeInterval;
@end
NSObject的+ PerformBlock.m
@interface NSObject (PerformBlockHidden)
- (void)performBlock:(void(^)(void))block;
@end
@implementation NSObject (PerformBlock)
- (void)performBlock:(void(^)(void))block {
block();
}
- (void)performBlock:(void(^)(void))block waitUntilDone:(BOOL)wait {
[self performSelector:@selector(performBlock:) onThread:nil withObject:[[block copy] autorelease] waitUntilDone:wait];
}
- (void)performBlock:(void(^)(void))block afterDelay:(NSTimeInterval)delay {
[self performSelector:@selector(performBlock:) withObject:[[block copy] autorelease] afterDelay:delay];
}
- (void)performBlock:(void(^)(void))block repeatCount:(NSUInteger)repeatCount timeInteval:(NSTimeInterval)timeInterval {
for (NSInteger repetition = 0; repetition < repeatCount; repetition++)
[self performBlock:block afterDelay:(repetition*timeInterval)];
}
@end
然后只需导入NSObject + PerformBlock.h并调用:
[myObject performBlock:^{
// Code you want to perform after 2secs
} afterDelay:2];
答案 3 :(得分:2)
您应该能够将NSTimeInterval
设置为2.0秒,并且应该在该时间后触发。你在看什么?你用来调用计时器的代码是什么?