iOS PTTextSearch locks main thread

Hi, I’m having an issue where, occasionally, my search function is locking the main thread, despite being queued to run on a background. The issue is more prominent on slower devices.

Below is my PTPDFDoc category method for performing search. Included in it is a OBDPDFSearchRequest object which I use to allow the caller to cancel a search in progress. I added that so I can cancel & search the document as a user types without needing to hit “Enter”.

Please advise if there is something I’m doing wrong that would cause a main thread lock, thanks!

  • (OBDPDFSearchRequest *)obd_searchForText:(NSString *)text completion:(void (^)(OBDPDFSearchRequest *request, NSArray<PTSearchResult *> *results))completion

{

NSParameterAssert(completion);

if (text.length == 0)

{

completion(nil, nil);

return nil;

}

OBDPDFSearchRequest *request = [[OBDPDFSearchRequest alloc] init];

request.isActive = YES;

request.searchString = text;

request.isCancelled = NO;

PTTextSearch *textSearch = [[PTTextSearch alloc] init];

unsigned int mode = e_pthighlight | e_ptambient_string;

__block NSMutableArray <PTSearchResult *> *results = [[NSMutableArray alloc] init];

__weak typeof(self) weakSelf = self;

dispatch_queue_t queue = dispatch_queue_create(“com.onboard.pdf.search”, DISPATCH_QUEUE_SERIAL);

dispatch_async(queue, ^{

[weakSelf Lock];

if (request.isCancelled == NO && [textSearch Begin:weakSelf pattern:text mode:mode start_page:-1 end_page:-1])

{

PTSearchResult *result = [textSearch Run];

[weakSelf Unlock];

while (result.IsFound == YES && request.isCancelled == NO)

{

[results addObject:result];

[weakSelf Lock];

result = [textSearch Run];

[weakSelf Unlock];

}

}

else

{

[weakSelf Unlock];

}

if (request.isCancelled == YES)

{

[results removeAllObjects];

}

dispatch_async(dispatch_get_main_queue(), ^{

request.isActive = NO;

completion(request, [NSArray arrayWithArray:results]);

});

});

return request;

}

Hi Brad,

What is the main thread blocking on? Because the text search needs to obtain a read lock on the document, if any other thread including the main thread requires a write lock, it will block until the search releases its lock. Does this explain what you’re seeing? (Maybe your app auto-saves every x seconds?)

James