4

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

我的应用在很大程度上依赖于这些通知,所以我想让应用在手机设置通知的同时工作。

例子:

(现在)

您启动应用程序,应用程序会挂在启动屏幕上以设置本地通知,然后启动。

(我想)

应用程序启动并在设置本地通知时可用。

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

(作为记录,每次应用程序出于我自己的原因进入前台时,我都会设置 60 个本地通知......)

谢谢!!

4

2 回答 2

3

做线程的一种方法是 with performSelectorInBackground

例如:

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

但是,您应该注意,Apple 强烈建议您使用更高级别的概念,例如NSOperations 和 Dispatch Queues,而不是显式生成线程。请参阅并发编程指南

于 2010-11-30T18:12:33.753 回答
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];
}

取自我现在正在进行的一个项目,我可以确认它按预期工作。

编辑:示例由于处理丢失
而泄漏- 现在它已添加到示例中。scheduleLocalNotificationsNSAutoreleasePool

于 2010-11-30T18:14:06.937 回答