Waiting for a specified duration in Cocoa

2019-02-02 21:50发布

Is there a more straightforward way to wait for a specific amount of time in Cocoa than what I have come up with below?

- (void) buttonPressed {
    [self makeSomeChanges];

    // give the user some visual feedback and wait a bit so he can see it
    [self displayThoseChangesToTheUser];
    [self performSelector:@selector(buttonPressedPart2:) withObject:nil afterDelay:0.35];
}

- (void) buttonPressedPart2: (id)unused {
    [self automaticallyReturnToPreviousView];
}

Just to be clear, there is no functional problem with this code -- my only beef is a stylistic one. In my case the flow is simple enough that it works, but try to encapsulate it or throw in some conditionals and things could turn ugly. It's been kind of nagging at me that I couldn't find a way to wait and then return to that same point in code like this (fictitious) example:

- (void) buttonPressed {
    [self doStuff];
    [UIMagicUnicorn waitForDuration:0.35];
    [self doStuffAfterWaiting];
}

7条回答
做自己的国王
2楼-- · 2019-02-02 22:23

I'm not sure if it exists (yet), but with blocks in 10.6 (or PLBlocks in 10.5 and on the iPhone) it should be pretty easy to write a little wrapper like performBlock:afterDelay: that does exactly what you want without the need to sleep the entire thread. Would be a useful little piece of code indeed.

Mike Ash has written about an approach like this on his blog:

NSString *something = ...;
RunAfterDelay(0, ^{
    NSLog(@"%@", something);
    [self doWorkWithSomething: something];
});
查看更多
登录 后发表回答