您的位置:首页 > 其它

Running a Method After A Delay on iPhone or Mac

2011-11-26 10:44 225 查看
In nearly every programming language there is a way to delay a method call. Objective-C is no different. They have built in a few simple methods to achieve this. We are going take a look at one of these methods today, all which reside in NSObject. This means
any class you create will have the ability to call these methods. The method we are going to take a gander at is
-(void)performSelector:(SEL)aSelector
withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
,
got the love the Objective-C method names.

This method is pretty self explanatory thanks to the super long name. Basically, we are going to run a method and pass in the object as the parameter for the method after a certain amount of time (in seconds). Okay, imagine we have built an application which
has a label that we want to change the text of after 5 seconds, why? I don't know, if the label keeps the same text for more than 5 seconds it will self destruct, anyway I digress. So, we create a method to change the text to something like the following:

-(void)changeText:(NSString*)text

{

myLabel.text = text;

}

The new method is about as simple as it gets, it changes the label's text to the passed in value. Now, in order to call this on a delay we need to use our aforementioned method,
-(void)performSelector:(SEL)aSelector
withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
.
In order to call our change text method with this it would look something like below.

[self performSelector:@selector(changeText:)
withObject:@"Hello" afterDelay:5];

This pretty much covers it. One note is that say you have a method that doesn't take a parameter like the one below.

-(void)changeText

{

myLabel.text = @"Hello";

}

Then if you want to call the method you pass in
nil
for the
withObject
argument,
like the following:

[self performSelector:@selector(changeText)
withObject:nil afterDelay:5];

另外一个延时方法可以用sleep(4)函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐