3

One question and one issue: I have the following code:

- (void) registerForLocalCalendarChanges
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(localCalendarStoreChanged) name:EKEventStoreChangedNotification object:store ];

}

- (void) localCalendarStoreChanged
{
    // This gets call when an event in store changes
    // you have to go through the calendar to look for changes
    [self getCalendarEvents];
}

These methods are in a class/object called CalendarEventReporter which contains the method getCalendarEvents (in the callback).

Two things: 1) If the app is in the background the callback does not run. Is there a way to make it do that? 2) When I bring the app back into the foreground (after having changed the calendar on the device) the app crashes without any error message in the debug window or on the device. My guess is that the CalendarEventReporter object that contains the callback is being garbage-collected. Is that possible? Any other thoughts on what might be causing the crash? Or how to see any error messages?

4

3 回答 3

4

1) 为了让应用程序在后台运行,您应该使用此处“后台执行和多任务处理”部分中提到的模式之一:

  • 使用定位服务
  • 录制或播放音频
  • 提供VOIP服务
  • 后台刷新
  • 通过 BLE 连接到外部设备

如果您不使用上述任何一种,则无法在后台获取异步事件。

2)为了查看崩溃日志/调用堆栈,请放置一个异常断点或查看“设备日志”部分:Window->Organizer->Devices->左侧的“设备名称”->Xcode上的设备日志。

于 2014-06-23T17:24:41.543 回答
1

要回答您的第一个问题,请查看https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

为了让代码在后台运行,我所做的是做类似的事情

在 .h 文件中

UIBackgroundTaskIdentifier backgroundUploadTask;

在 .m 文件中

-(void) functionYouWantToRunInTheBackground
{    
    self.backgroundUploadTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
}];
//code to do something
}

-(void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUploadTask];
    self.backgroundUploadTask = UIBackgroundTaskInvalid;
}

上面的代码我从objective c中学到了很多——正确使用beginBackgroundTaskWithExpirationHandler

至于您的第二个问题,您应该设置一个断点,当您将应用程序带回前台时应该运行代码。如果没有提供足够的代码或信息,没有人能弄清楚为什么应用程序会崩溃。

于 2014-06-23T15:02:10.033 回答
1

问题第二部分的解决方案是提高包含回调代码的对象的范围。我将它提升到包含 ViewController 的级别。这似乎有效。如果在应用程序处于后台/暂停状态时出现通知,我仍然无法弄清楚如何引发通知(即执行回调)。这阻止了包含回调的对象被清理。

于 2014-06-24T13:12:14.650 回答