我有一个NSOperationQueue,maxConcurrentOperationCount = 1。

所有操作都通过以下方式添加到NSOperationQueue中:addOperationWithBlock:

现在,发生低频崩溃,调用堆栈如下。

 Crashed: NSOperationQueue :: NSOperation 0x14fbf2d20 (QOS: LEGACY)
0  libobjc.A.dylib                0x1811a8160 objc_release + 16
1  MyApp                          0x1015437f0 -[MyClass .cxx_destruct] (MyClass.m:23)
2  libobjc.A.dylib                0x18118eb54 object_cxxDestructFromClass(objc_object*, objc_class*) + 148
3  libobjc.A.dylib                0x18119a040 objc_destructInstance + 92
4  libobjc.A.dylib                0x18119a0a0 object_dispose + 28
5  MyApp                          0x101546aec __destroy_helper_block_ (MyNSOperationQueue.m)
6  libsystem_blocks.dylib         0x1815d18e8 _Block_release + 156
7  Foundation                     0x182437f8c -[NSBlockOperation dealloc] + 64
8  Foundation                     0x1824e6a18 __NSOQSchedule_f + 452
9  libdispatch.dylib              0x18157547c _dispatch_client_callout + 16
10 libdispatch.dylib              0x1815814c0 _dispatch_queue_drain + 864
11 libdispatch.dylib              0x181578f80 _dispatch_queue_invoke + 464
12 libdispatch.dylib              0x181583390 _dispatch_root_queue_drain + 728
13 libdispatch.dylib              0x1815830b0 _dispatch_worker_thread3 + 112
14 libsystem_pthread.dylib        0x18178d470 _pthread_wqthread + 1092
15 libsystem_pthread.dylib        0x18178d020 start_wqthread + 4

主要代码如下。
@interface MyNSOpetationQueue ()

@property (nonatomic, strong) NSOperationQueue *operationQueue;

@end

@implementation MyNSOpetationQueue

#pragma mark - init

+ (MyNSOpetationQueue *)sharedSender {
    static MyNSOpetationQueue *analyticsSender = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
        analyticsSender = [[MyNSOpetationQueue alloc] init];
    });

    return analyticsSender;
}

- (instancetype)init {
    if ((self = [super init])) {
        _operationQueue = [[NSOperationQueue alloc] init];
        [_operationQueue setMaxConcurrentOperationCount:1];
    }

    return self;
}

#pragma mark public method

- (void)addOneObj:(MyClass *)obj {
    if (!obj) {
        return;
    }

    __weak typeof(self) weakSelf = self;
    [self.operationQueue
     addOperationWithBlock:^{
         __strong typeof(weakSelf) strongSelf = weakSelf;
         //1.insert `obj` to Sqlite
         //2.do other thing
     }];
}

@end

最佳答案

我认为您在这两行代码__weak typeof(self) weakSelf = self; and __strong typeof(weakSelf) strongSelf = weakSelf;中的问题尝试将其删除。

- (void)addOneObj:(MyClass *)obj {
    if (!obj) {
        return;
    }

    [self.operationQueue addOperationWithBlock:^{
         //1.insert `obj` to Sqlite
         //2.do other thing
     }];
}

您的addOperationWithBlock捕获了自我,超出范围将销毁。在这种情况下,无需弱引用自己

关于ios - iOS-cxx_destruct中的EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38842247/

10-10 21:00