NSNotification发布主线程崩溃

时间:2013-08-29 10:16:18

标签: ios objective-c grand-central-dispatch nsnotificationcenter nsnotification

我有一个Notification Manager类,它应该在主线程上发布所有通知。但我有一些崩溃报告。该应用程序在此行崩溃:

dispatch_sync(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject];

我想知道如何解决这个问题。 Thx提前

#import "NotificationManager.h"

@interface NotificationManager ()
{
    NSNotificationCenter *center;
}
@end

@implementation NotificationManager

+ (NotificationManager *) sharedInstance
{
    static NotificationManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NotificationManager alloc] init];
    });
    return instance;
}

- (void) postNotificationName:(NSString *)aName object:(id)anObject
{
    if (dispatch_get_current_queue() != dispatch_get_main_queue())
    {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject];
        });
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject];
    }
}
@end

崩溃报告:

7   PLR 0x000e5d40  __51-[NotificationManager postNotificationName:object:]_block_invoke in NotificationManager.m on Line 27
8   libdispatch.dylib   0x39a14a88  _dispatch_barrier_sync_f_slow_invoke
9   libdispatch.dylib   0x39a105da  _dispatch_client_callout
10  libdispatch.dylib   0x39a13e44  _dispatch_main_queue_callback_4CF
11  CoreFoundation  0x318cf1b0  __CFRunLoopRun
12  CoreFoundation  0x3184223c  CFRunLoopRunSpecific
13  CoreFoundation  0x318420c8  CFRunLoopRunInMode
14  GraphicsServices    0x3542133a  GSEventRunModal
15  UIKit   0x3375e2b8  UIApplicationMain
16  PLR 0x000c5b4a  main in main.m on Line 9

1 个答案:

答案 0 :(得分:3)

我不能说这是否能解决您的问题,但您的-postNotificationName:object:方法可能更好地编写如下:

- (void) postNotificationName:(NSString *)aName object:(id)anObject
{
    if (![NSThread isMainThread])
    {
        dispatch_sync(dispatch_get_main_queue(), ^{ [self postNotificationName: aName object: anObject]; });
        return;
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject];
}