1

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

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

我想得到一个建议如何解决这个问题。提前谢谢

#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
4

1 回答 1

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];
}
于 2013-08-30T11:39:26.423 回答