fel*_*lix 2 iphone objective-c nsnotifications iphone-sdk-3.0
在iPhone SDK 3.0中,我想注册一个通知,该通知会在达到特定时间时提醒我的应用程序.可能吗?谢谢
设置NSTimer一个每30秒运行一个选择器(或您需要的任何粒度):
[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)
该-timerFired:选择器(方法)将运行每隔30秒,检查时,分和第二组分,发射的通知,如果元素匹配所需时间:
- (void) timerFired:(NSNotification *)notification {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger hour = [dateComponents hour];
NSInteger min = [dateComponents minute];
NSInteger sec = [dateComponents second];
if ((hour == kDesiredHour) && (min == kDesiredMinute) && (sec == kDesiredSecond)) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"kTimeComponentsWereMatched" object:nil userInfo:nil];
}
}
Run Code Online (Sandbox Code Playgroud)
您注册在某处的某个其他类中侦听此通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"kTimeComponentsWereMatched" object:nil];
Run Code Online (Sandbox Code Playgroud)
因此,你在同一个类中有一个方法可以做一些有趣的事情:
- (void) doSomething:(NSNotification *)notification {
// do something interesting here...
}
Run Code Online (Sandbox Code Playgroud)
如果它在一个类中,则可以合并此代码.或指定target的NSTimer指向要运行的类的实例selector英寸
| 归档时间: |
|
| 查看次数: |
2868 次 |
| 最近记录: |