我正在尝试练习块和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运行单元测试
这是错误消息: 对象0xa0f8000的otest(11105,0xb039f000)malloc: * 错误:未分配被释放的指针
otest(11209,0xb0115000)malloc: *对象0x41dcc00的错误:未释放指针被释放 * 在malloc_error_break中设置断点以进行调试
这次我无法重现'双重免费'错误