我需要知道是否可以创建一个新线程来处理设置本地通知。
我的应用程序在很大程度上取决于这些通知,因此我希望在手机设置通知时让应用程序正常工作。
示例:
(现在)
启动应用后,应用会在启动画面挂起以设置本地通知,然后启动。
(我想)
应用程序启动并在设置本地通知时可用。
我也需要一些示例代码,请:)
(对于记录,我每次应用程序因为我自己的原因进入前台时都会设置60个本地通知...)
谢谢!
答案 0 :(得分:3)
执行线程的一种方法是使用performSelectorInBackground
。
例如:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
但是,您应该注意,Apple非常强烈建议您使用更高级别的概念,例如NSOperation
和Dispatch Queues,而不是显式生成线程。请参阅Concurrency Programming Guide
答案 1 :(得分:3)
是的,这可以做到,我一直这样做:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add the navigation controller's view to the window and display.
[NSThread detachNewThreadSelector:@selector(scheduleLocalNotifications) toTarget:self withObject:nil];
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
return YES;
}
-(void) scheduleLocalNotifications
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i < 60; i++)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
NSLog(@"Sleepdate is: %@", sleepDate);
localNotif.fireDate = sleepDate;
NSLog(@"fireDate is %@",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"This is local notification %i"), i];
localNotif.alertAction = NSLocalizedString(@"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
[localNotif release];
}
[pool release];
}
从我正在进行的项目中获取,我可以确认它按预期工作。
修改强>
示例在scheduleLocalNotifications
中泄漏,因为缺少处理NSAutoreleasePool
- 现在它已添加到示例中。