2010-11-30 46 views
4

我需要知道是否有可能创建一个新线程来处理设置本地通知。在新线程上设置本地通知?

我的应用程序在很大程度上依赖于这些通知,因此我希望在手机设置通知时使应用程序正常工作。

例子:

(现在)

你启动应用程序,该应用程序在启动画面挂起设置本地通知,然后将其启动。

(我想)

应用程序启动和而本地通知设置是可用的。

我需要一些示例代码,也请:)

(备案,我设置的每个应用程序进入前景为我自己的原因时...... 60个本地通知)

谢谢! !

回答

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失踪 - 现在它加入的例子。

3

执行线程的一种方法是用performSelectorInBackground

例如:

[myObj performSelectorInBackground:@selector(doSomething) withObject:nil]; 

您应该注意,但是,苹果是相当强烈建议您使用更高级的概念,如NSOperation S和调度队列而是明确产卵线程。见Concurrency Programming Guide

+0

感谢您的贡献! – Mazyod 2010-11-30 18:30:13

+0

它崩溃的更多。 :( – 2013-10-23 06:26:52