【发布时间】:2011-05-17 13:39:51
【问题描述】:
我正在开发适用于 Mac OS X 的应用程序。我的应用程序每十秒检查一次,如果条件为真,应用程序会发送 Growl 通知。
我已经编写了 Growl 通知和检查代码。我只需要知道如何让这种检查每十秒重复一次,并且每次如果为真则在后台发送通知。
请写出准确的代码,因为我是 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
【问题讨论】:
-
永远不要在应用程序主线程上运行的方法中使用
sleep()。整个 UI 将冻结这段时间。 -
概括:永远不要使用
sleep()。 -
还有;鉴于您为回答答案而提出的问题的基本性质,我建议您阅读 Objective-C 和 Cocoa 入门指南。他们会很有帮助。
-
此外,尽可能不要轮询事物,即使是在计时器上。最好使用不同的机制(例如
kqueue),这样您的应用程序就不会消耗不必要的 CPU 周期,或者(更糟糕的是)无意中使机器无法进入睡眠状态。
标签: objective-c cocoa macos background