【问题标题】:Setting Local Notifications on a new thread?在新线程上设置本地通知?
【发布时间】:2010-11-30 17:58:26
【问题描述】:

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

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

例子:

(现在)

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

(我想要)

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

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

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

谢谢!!

【问题讨论】:

    标签: iphone multithreading ios4 nsthread uilocalnotification


    【解决方案1】:

    是的,这可以做到,我一直这样做:

    - (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 - 现在它已添加到示例中。

    【讨论】:

    • 嘿,np.. 这就是我们来这里的目的
    • 在主线程外使用 UIApplication 是不安全的,可能会导致“意外结果”。我会质疑为什么你需要在线程之外进行。我怀疑它占用了很多时间。如果它需要离开线程,你仍然需要在主线程上运行'scheduleLocalNotification'以确保安全。
    【解决方案2】:

    处理线程的一种方法是使用performSelectorInBackground

    例如:

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

    但是,您应该注意,Apple 强烈建议您使用更高级别的概念,例如 NSOperations 和调度队列,而不是显式生成线程。见Concurrency Programming Guide

    【讨论】:

    • 感谢您的贡献!
    • 它崩溃得更厉害了。 :(
    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 2011-11-21
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多