oc block 防止 strong capture需要这么写?
2017-08-05 本文已影响57人
2d899c5242bd
afnetworking 中曾有这样一段代码,是维护者防止block强持有 task对象做的修改
__weak __typeof__(task) weakTask = task;
[self.uploadProgress setCancellationHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask cancel];
}];
这里叫个真,想知道block中是否__typeof__(task) strongTask = weakTask;
会导致task 被强持有,于是做了如下测试:
测试类
#import <Foundation/Foundation.h>
@interface BlockClass : NSObject
@property (nonatomic,copy) void (^blockName)();
@end
#import "BlockClass.h"
@implementation BlockClass
- (void)dealloc
{
NSLog(@"%s", __FUNCTION__);
}
@end
test case模拟 client
#import <XCTest/XCTest.h>
#import "BlockClass.h"
@interface BlockClassTests : XCTestCase
@property (nonatomic,strong) BlockClass *blockObj;
@end
@implementation BlockClassTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
BlockClass *blockObj = [[BlockClass alloc] init];
__weak typeof(blockObj) weakObj = blockObj;
blockObj.blockName = ^{
__strong typeof(blockObj) strongObj = weakObj;
// id obj = blockObj;//我是注释 2
};
self.blockObj = blockObj;
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
self.blockObj = nil;
}
- (void)testExample {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
XCTAssertTrue(self.blockObj.blockName != nil);
}
@end
查证,控制台会输出
2017-08-05 16:57:09.345 OperationQueueTest[26460:10245855] -[BlockClass dealloc]
倘若将注释2 打开,则会导致强持有了。
我的结论是