简单的 NSThread 或 NSTimer
我想运行某些后台任务。
场景:我想要一个按钮来激活线程或计时器,然后让线程/计时器开始重复每秒向用户返回一个带有数据的 NSRunInformationalAlertPanel。
这就是我的计时器的内容:
-(void)workerThread:(NSTimer*) theTimer {
if(intNumberOfTicks > 0)
{
NSRunInformationalAlertPanel(@"The Serial", [NSString stringWithFormat:@"%d", intNumberOfTicks], @"OK", nil, nil);
//[txtTimeMinutes setStringValue:[NSString stringWithFormat:@"%d", intNumberOfTicks]];
intNumberOfTicks--;
}
else {
[timer invalidate];
}
}
以及启动该方法...
intNumberOfTicks = 5;
timer = [[NSTimer scheduledTimerWithTimeInterval:1 target: self selector:@selector(workerThread:) userInfo:self repeats:true] retain];
// Or for threading...
///[NSThread detachNewThreadSelector:@selector(workerThread) toTarget:self withObject:nil];
任何人都可以帮助我实现我需要的东西,也许提供 NSThread 或 NSTimer 的最基本的示例。我看过 Apple Dev Refrences 但没有运气。
I want to run certain background tasks.
Scenario: I would like a button to activate a thread or timer, and then have the thread/timer to start repeating every second returning a NSRunInformationalAlertPanel to the user with data.
This is what I have for my timer:
-(void)workerThread:(NSTimer*) theTimer {
if(intNumberOfTicks > 0)
{
NSRunInformationalAlertPanel(@"The Serial", [NSString stringWithFormat:@"%d", intNumberOfTicks], @"OK", nil, nil);
//[txtTimeMinutes setStringValue:[NSString stringWithFormat:@"%d", intNumberOfTicks]];
intNumberOfTicks--;
}
else {
[timer invalidate];
}
}
And for starting the method...
intNumberOfTicks = 5;
timer = [[NSTimer scheduledTimerWithTimeInterval:1 target: self selector:@selector(workerThread:) userInfo:self repeats:true] retain];
// Or for threading...
///[NSThread detachNewThreadSelector:@selector(workerThread) toTarget:self withObject:nil];
Can anyone help me implement what I need, maybe providing the most basic examples for a NSThread or NSTimer. I have looked at the Apple Dev Refrences but no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 NSTimer 将在与实例化和调用它的线程相同的线程中执行选择器。
如果您的任务必须在后台线程中执行,请尝试调用 PerformSelectorInBackground:withObject:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorInBackground: withObject:
从该后台线程,您可以按照上面描述的方式使用计划的计时器。
Using NSTimer will execute the selector in the same thread as the one which instantiated and invoked it.
If your task must be carried out in a background thread try calling performSelectorInBackground:withObject:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorInBackground:withObject:
From that background thread you can use a scheduled timer the way that you described above.