I'm making an app which searches texts (enumerating through the whole text via a block method). The search controller class is supposed to compile the results into an array, which is then returned via a delegate method.
I know the search logic is working, because before I added the delegate method I was getting results, and my resultsCount integer is still logging the expected number of results. What I've changed is to call this method in a queue, and dispatch it back to the main queue as follows:
searchQueue = dispatch_queue_create("searchQueue", NULL);
dispatch_async(searchQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^ {
[controller performSearchWithString:searchText andTexts:[self textsToSearch]];
});
Since I did this, my actual array is not picking up any of these objects (or it's immediately dumping them?)--it always logs "null". I have no idea why. Declaring the array as a __block object does not change it, nor does creating it as a property of the class. Here's my code for the method:
-(void)performSearchWithString:(NSString *)searchString andTexts:(NSSet *)texts
{
NSMutableArray *pendingResults = nil;
__block int resultsCount = 0;
NSError *error = nil;
for (id book in texts) {
if ([book isEqual:kBook1]){
NSURL *url = [[NSBundle mainBundle] URLForResource:@"neiJing" withExtension:@"txt"];
NSString *text = [NSString stringWithContentsOfURL:url encoding:NSStringEncodingConversionAllowLossy error:&error];
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
//NSRange found = [substring rangeOfString:text];
if ([searchString caseInsensitiveCompare:substring] == NSOrderedSame) {
SearchResult *result = [[SearchResult alloc] init];
result.title = @"neiJing";
result.author = @"Author";
//result.excerpt = substring; // Add logic to configure excerpt range
result.range = NSMakeRange(substringRange.location-500, substringRange.length + 500);
result.excerpt = [NSString stringWithFormat:@"...%@...",[text substringWithRange:result.range]];
[pendingResults addObject:result];
NSLog(@"%@", pendingResults);
resultsCount++;
}
}];
}
if (error == nil) {
[self.delegate SearchControllerDidReturnResults:[NSArray arrayWithArray:pendingResults]];
}
Greatly appreciate any help. I'm still really struggling to understand blocks, not having any background in straight "C", but thought I had a grasp of how variable scope was affected. Seems I'm still missing a critical concept.