本文介绍了如何使自己在MRC中变得虚弱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Message *m = [msg retain];
dispatch_queue_t queue = _handle_queue;
__block ProtocolDriver* blockSelf = self;
dispatch_async(queue, ^{
    if (blockSelf.protocol_delegate && [blockSelf.protocol_delegate respondsToSelector:@selector(onReceive:)]) {
        [blockSelf.protocol_delegate onReceive:m];
    }
});

我有一个MRC Objective-C文件,该文件需要异步在块中运行一些代码.

I have a MRC objective-c file, which need run some code in block asynchronously.

但是我认为blockself是不安全的,因为它不是弱指针,是否应该将其更改为真正的弱指针.

But I thought the blockself is not safe since it is not weak pointer, Should I change it to true weak pointer.

@interface WeakPtr : NSObject
@property (nonatomic, weak) id realObj;
@property (nonatomic, assign) bool released;
@end
@implementation WeakPtr
@end

设置释放MRC对象时的释放状态,并在块中进行测试

set the released when the MRC-object is dealloced, and test it in block

@property (nonatomic, retain) WeakPtr* selfPtr;
- (id)init{
    ...
    self.selfPtr = [[[WeakPtr alloc] init] autorelease];
    self.selfPtr.realObj = self;
}

- (void)dealloc
{
    ...
    self.selfPtr.released = true;
}

-(void)pump: (Message *)msg
{
    Message *m = [msg retain];
    dispatch_queue_t queue = _handle_queue;

    __block WeakPtr* weakSelf = self.selfPtr;
    dispatch_async(queue, ^{
        if (!weakSelf.released && [weakSelf.protocol_delegate respondsToSelector:@selector(onReceive:)]) {
            [weakSelf.protocol_delegate onReceive:m];
        }
    });
}

推荐答案

是的,当然.

1)创建一个ARC弱指针包装器类.

1) make a ARC weak pointer wrapper class.

@interface WeakPtr : NSObject
@property (nonatomic, weak) id realObj;
@end
@implementation WeakPtr
@end

2)在MRC中使用ARC弱指针包装器包装强指针.

2) use the ARC weak pointer wrapper in MRC to wrap the strong pointer.

-(void)pump: (Message *)msg
{
    Message *m = [msg retain];
    dispatch_queue_t queue = _handle_queue;
    WeakPtr* weakPtr = [WeakPtr new];
    weakPtr.realObj = self;
    dispatch_async(queue, ^{
        if ([weakPtr.realObj.protocol_delegate respondsToSelector:@selector(onReceive:)]) {
            [weakPtr.realObj.protocol_delegate onReceive:m];
        }
        [weakPtr release];
    });
}

另一个选项是-fobj-weak编译器标志.

Another option is -fobj-weak compiler flag.

这篇关于如何使自己在MRC中变得虚弱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:52