gpt4 book ai didi

iphone - 在 iPhone SDK 3.0 中注册通知

转载 作者:行者123 更新时间:2023-12-03 20:27:04 25 4
gpt4 key购买 nike

在 iPhone SDK 3.0 中,我想注册一个通知,当达到特定时间时它会提醒我的应用程序。是否可以?谢谢

最佳答案

设置一个 NSTimer 每 30 秒运行一次选择器(或您需要的任何粒度):

 [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

-timerFired: 选择器(方法)将每三十秒运行一次并检查小时、分钟和秒部分,如果元素与所需时间匹配则触发通知:

 - (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];
}
}

您在其他类(class)的某个地方注册监听此通知:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"kTimeComponentsWereMatched" object:nil];

因此,同一个类中有一个方法可以做一些有趣的事情:

 - (void) doSomething:(NSNotification *)notification {
// do something interesting here...
}

如果此代码全部位于一个类中,则可以合并该代码。或者在 NSTimer 中指定 target 以指向要在其中运行选择器的类实例。

关于iphone - 在 iPhone SDK 3.0 中注册通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1452773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com