我正在尝试练习块和 GCD/NSOperation,所以我编写了这个项目Async-objc,但是当我尝试使用单元测试对其进行测试时,我总是遇到“双重释放”错误,我认为不应该在ARC模式下会出现这样的错误。
这是代码
- (void)each:(NSArray *)items iterator:(callbackEach)iterator complete:(callbackWithError)complete {
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
if (!items || items.count == 0) {
complete(nil);
return;
}
callbackWithError __block completeOnce = complete;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(@"start operations %@", queue);
[queue setMaxConcurrentOperationCount:kMaxConcurrentOperationCount];
NSInteger __block count = 0;
for (id item in items) {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
iterator(item, ^(NSError *error) {
if (error) {
completeOnce(error);
completeOnce = nil;
} else {
count++;
if (count >= items.count) {
completeOnce(nil);
completeOnce = nil;
}
}
});
}];
[queue addOperation:op];
}
[queue waitUntilAllOperationsAreFinished];
NSLog(@"all operations are down %@", queue);
}];
[_mainQueue addOperation:blockOp];
}
这是测试代码:
- (void)testEachWithBigData {
BOOL __block completed = false;
NSMutableArray *items = [NSMutableArray arrayWithCapacity:100];
for (int i = 1; i < 10000; ++i) {
[items addObject:[NSString stringWithFormat:@"%d", i]];
}
NSMutableArray *result = [NSMutableArray arrayWithCapacity:100];
[_async each:items
iterator:^(id item, callbackWithError callback) {
//NSLog(@"======item %@", item);
NSNumber *num = [NSNumber numberWithInt:[item integerValue]];
//NSLog(@"number %@", num);
[result addObject:num];
callback(nil);
}
complete:^(NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
STAssertNil(error, @"there should be no error");
[result sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *num1 = (NSNumber *)obj1;
NSNumber *num2 = (NSNumber *)obj2;
if ([num1 integerValue] > [num2 integerValue]) {
return NSOrderedDescending;
} else if ([num1 integerValue] < [num2 integerValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
NSInteger index = 1;
for (NSNumber *num in result) {
STAssertEquals(index, [num integerValue], @"the value should be ordered");
index++;
}
completed = YES;
});
}
];
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:10];
while (!completed && [until timeIntervalSinceNow] > 0) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:until];
}
}
如果您无法重现错误,请将测试项目数增加到 10000。
for (int i = 1; i < 10000; ++i) {
[items addObject:[NSString stringWithFormat:@"%d", i]];
}
并评论 NSLog() 然后 Command + U 运行单元测试
这是错误消息:otest(11105,0xb039f000) malloc: *对象 0xa0f8000 的错误:未分配指针被释放
otest(11209,0xb0115000) malloc: * 对象 0x41dcc00 的错误:未分配被释放的指针 *在 malloc_error_break 中设置断点以进行调试
这次我无法重现“双重免费”错误