2

UIAlertView在主线程上显示 a 时遇到问题。我不知道为什么,但它一直在崩溃,尽管我在主线程上运行。以下块在后台线程上,但我在主线程上有如下警报:

void (^removeFromCalendar)(NSString *, NSString *, EKEventStore *) = ^(NSString *error, NSString *eventKey, EKEventStore *eventDB) {
    EKEvent *myEvent = [eventDB eventWithIdentifier:eventKey];
    NSError *err = noErr;

    if(myEvent != NULL && myEvent != (id)[NSNull null]) {
        [eventDB removeEvent:myEvent span:EKSpanThisEvent error:&err];
    } else {

        // Event was not found, nothing to do
        return;
    }

    [eventDB release];

    if (!err || err == noErr) {
        NSLog(@"Deleted event %@", myEvent.title);

        // Show alert on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            // Showing the alert for unattending
            NSString *resultString = @"This event was removed from your calendar.";
            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Info" message:resultString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];
            [alert show];
        });

        return;
    }

    error = err.description;
};

如果我注释掉显示警报的底部,一切都很好。但是对于警报,我不断收到EXC_BAD_ACCESS错误消息。有人可以解释为什么吗?它在正确的线程上,我一生都无法理解内存问题可能来自哪里!

4

3 回答 3

1

完成后,您的视图可能会被释放,直到您完成后台队列。所以,为了安全,你为什么不这样使用它;

...........
  UIViewController __weak *myController = self;
 dispathch_async(backgroundQueue, ^{ 
   UIViewController __strong *myStrongController = myController;
 ...............
 dispatch_async(dispatch_get_main_queue(), ^{
            if(myStrongController){
            // Showing the alert for unattending
            NSString *resultString = @"This event was removed from your calendar.";
            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Info" message:resultString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];
            [alert show];
            }
        });
}).
于 2012-11-23T20:50:05.117 回答
0

这是您呈现警报视图的方式:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"<#(NSString *)#>" message:@"<#(NSString *)#>" delegate:self cancelButtonTitle:@"<#(NSString *)#>" otherButtonTitles:nil];
    [alert show];
    [alert release];
于 2012-11-23T19:21:04.167 回答
0

为什么不使用目标 C 调用,而不是使用 dispatch_async:

[self performSelectorOnMainThread

您可能必须将其打包到自己的方法中。或者,使用以下方法调用它:

[self performSelector:@selector(myAlertMethod) withObject:nil afterDelay:0.25]

从第一天开始,这些方法就已经被尝试过并且是正确的。

于 2012-11-24T04:21:10.610 回答