我正在为Mac开发一个应用程序。我的应用程序每十秒检查一次,如果条件为真,应用程序会发送一个咆哮通知。
我已经对咆哮通知和检查进行了编码。我只需要知道如何让这个检查每10秒重复一次,如果是真的,每次都会在后台发送一个通知。
请编写准确的代码,因为我对Objective-C非常陌生。谢谢你:D
目前我使用的是:
// MyApp_AppDelegate.m
#import "MyApp_AppDelegate.h"
@implementation MyApp_AppDelegate
- (void)awakeFromNib {
return;
}
-(void)applicationDidFinishLaunching:(NSNotification*)aNotification {
// grwol:
NSBundle *myBundle = [NSBundle bundleForClass:[MyApp_AppDelegate class]];
NSString *growlPath = [[myBundle privateFrameworksPath] stringByAppendingPathComponent:@"Growl-WithInstaller.framework"];
NSBundle *growlBundle = [NSBundle bundleWithPath:growlPath];
#include <unistd.h>
int x = 0;
int l = 10; // time/repeats
int t = 10; //seconds
while ( x <= l ) {
// more code here only to determine sendgrowl value...
if(sendgrowl) {
if (growlBundle && [growlBundle load]) {
// more code to sends growl
} else {
NSLog(@"ERROR: Could not load Growl.framework");
}
}
// do other stuff that doesn't matter...
// wait:
sleep(t);
x++;
}
}
/* Dealloc method */
- (void) dealloc {
[super dealloc];
}
@end发布于 2011-05-17 21:42:29
您正在寻找的确切代码可以在以下位置找到:Time Programming Topics
发布于 2011-05-17 22:43:32
-(void) sendGrowl { } // your growl method
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self
selector:@selector(sendGrowl) userInfo:nil repeats:YES]; 完成计时器后,调用[timer invalidate]。粘贴到XCode并对其执行alt+click操作以读取文档。
发布于 2011-05-17 22:44:12
要将计时器安排为每10秒运行一次,需要执行以下操作:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 10.0
target: someObject
selector: @selector(fire:)
userInfo: someParameter
repeats: YES];这将创建一个计时器,并将其放在run循环中,以便每10秒触发一次。当它触发时,它等同于下面的方法调用:
[someObject fire: someParameter];您可以将nil作为someParameter传递,在这种情况下,您的选择器不需要带参数,即它可以是-fire而不是-fire:。
要停止计时器,只需向其发送invalidate消息。
[timer invalidate];计时器需要运行循环才能工作。如果您在应用程序的主线程上运行它,这是很好的,因为主线程已经有一个run循环(它处理UI事件并将它们传递给您的操作)。如果希望计时器在不同的线程上触发,则必须在该不同的线程上创建并运行一个run循环。这有点高级,所以如果你是Objective-C的新手,现在就避免使用它。
编辑
在看到您正在尝试做的事情之后,调度计时器的第一段代码需要替换整个while循环。-fire方法看起来类似于:
-fire
{
// code here only to determine sendgrowl value...
if(sendgrowl)
{
if (growlBundle && [growlBundle load])
{
// more code to sends growl
}
else
{
NSLog(@"ERROR: Could not load Growl.framework");
}
}
// do other stuff that doesn't matter...
}https://stackoverflow.com/questions/6031651
复制相似问题