我正在为函数包装for循环以启用多个html到多个pdf转换:
for (int i=0; i<= 47; i++) {
NSString *inputHTMLfileName = [NSString stringWithFormat:@"wkhtml_tempfile_%d",j];
NSString *outputPDFfileName = [NSString stringWithFormat:@"~/Documents/%d_delegateDemo%d.pdf",loop,j];
NSURL *htmlFileUrl = [[NSBundle mainBundle]
URLForResource:inputHTMLfileName withExtension:@"html"];
// Check for existing pdf file and remove it
NSError *pdfDeleteError;
if ([[NSFileManager defaultManager] fileExistsAtPath:outputPDFfileName]){
//removing file
if (![[NSFileManager defaultManager] removeItemAtPath:outputPDFfileName error:&pdfDeleteError]){
NSString * errorMessage = [NSString stringWithFormat:@"wk %d Could not remove old pdf files. Error:%@",j, pdfDeleteError];
NSLog(@"%@",errorMessage);
}
}
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:htmlFileUrl pathForPDF:[outputPDFfileName stringByExpandingTildeInPath] pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath];
NSLog(@"%@",result);
self.resultLabel.text = result;
} errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did fail (%@)", htmlToPDF];
NSLog(@"%@",result);
self.resultLabel.text = result;
}];
}
然而,它崩溃了
线程1:EXC_BAD_ACCESS(代码= EXC_I386_GPFLT)
链接到github:https://github.com/iclems/iOS-htmltopdf
但是,如果我用按下的按钮替换for循环(每秒触发此功能一次),应用程序不会崩溃。
我认为你的for循环崩溃是因为你在for循环中使用了block
所以这里发生的是在块完成前一个块调用之前调用块的另一个迭代
所以在这里你可以做什么,你可以使用ios的dispatch_group功能来调用不同线程上的每个迭代调用,而不是顺序调用
所以为了实现这个,你可以使用block参数创建一个方法,并在该方法中调用块,这样的事情,
- (void)blockTask:(NSString*)strPath
{
dispatch_group_enter(serviceGroup);
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:htmlFileUrl pathForPDF:[outputPDFfileName stringByExpandingTildeInPath] pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath];
NSLog(@"%@",result);
self.resultLabel.text = result;
dispatch_group_leave(serviceGroup);
} errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did fail (%@)", htmlToPDF];
NSLog(@"%@",result);
self.resultLabel.text = result;
dispatch_group_leave(serviceGroup);
}];
}
注意:这只是一个伪代码可能包含错误,对于调度组教程检查qazxsw poi