Вы также можете использовать удобный код:
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];