Пожалуйста, позвольте мне уточнить, что я делаю и что происходит. Я новичок в какао и объектив-с. Пожалуйста, будьте немного снисходительны. Спасибо.COCOA: Невозможно нажать кнопку ОТМЕНА, пользовательский интерфейс зависает и не отвечает, как с этим бороться?
Что я делаю
Я создаю утилиту поиска файлов, где пользователь может ввести ключевое слово и приложение какао будет искать целые системные файлы и, если ключевое слово присутствует в файле пути тогда это шоу это пользователю.
Проблема
При нажатии на кнопку CANCEL интерфейс получает руку и перестает отвечать на запросы.
Coding часть начинается здесь:
библиотека
/// this funciton will be called with
/// keyword : the word that should be present in the file path
/// selector : a function tha will be called when ever the function will find a matching file
/// selector: object of the class that has the funciton (selector)
-(NSMutableArray *)searchWholeSystem:(NSString *)keyword
selector:(SEL)aselector
target:(id)atarget
{
/// _cancelSearch is a property which can be set by the user of the class
/// when the scann will be started it will be set to as default : NO
_cancelSearch = NO;
/// list of all the files that are matched with the keyword
NSMutableArray* fileList = [[NSMutableArray alloc]init];
///autoreleasepool to release the unused memory
@autoreleasepool {
///getMainDirectories is local function that will get the user direcotires or the target direcoties where the search will be done
NSMutableArray* directories = [self getMainDirectories];
///one by one search all the direcoties for the matching files
for (NSString* dir in directories) {
NSMutableArray* resultList = [self getAllFiles:dir tag:keyword target:atarget selector:aselector];
for (int i = 0; i<[resultList count]; i++) {
///if cancel then return the as yet result array
if (_cancelSearch)
return fileList;
NSString* path = [resultList objectAtIndex:i];
GenericResultModel* sfile = [[GenericResultModel alloc]init];
sfile.Column1 = [path lastPathComponent];
sfile.Column2 = path;
[fileList addObject:sfile];
}
}
return fileList;
}
}
///getAllFiles will be having
///sPath : source path where the search will be performed
///tag: tag is the keyword that need to found in the path
/// selector : a function tha will be called when ever the function will find a matching file
/// selector: object of the class that has the funciton (selector)
-(NSMutableArray*)getAllFiles:(NSString*)sPath tag:(NSString*)_tag target:(id)atarget selector:(SEL)aselector
{
// fileList is the result that will contain all the file names that has the _tag
NSMutableArray* fileList = [[NSMutableArray alloc]init];
@autoreleasepool {
// _tag is the keyword that should be present in the file name
_tag = [_tag lowercaseString];
///getting all contents of the source path
NSArray *contentOfDirectory=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:sPath error:NULL];
for(int i=0; i < [contentOfDirectory count]; i++)
{
if (_cancelSearch)
return fileList;
NSString *filePathInDirectory = [contentOfDirectory objectAtIndex:i];
NSString* fullPath = [NSString stringWithFormat:@"%@/%@", sPath, filePathInDirectory];
if ([FMH isdirOrApp:fullPath])
{
if ([[fullPath lowercaseString] rangeOfString:_tag].location != NSNotFound && [fileList indexOfObject:fullPath] == NSNotFound)
{
[fileList addObject:fullPath];
[atarget performSelector:aselector withObject:fullPath];
}
if (_cancelSearch)
return fileList;
NSMutableArray* files = [self getAllFiles:fullPath tag:_tag target:atarget selector:aselector];
for (NSString* f in files)
{
if ([[f lowercaseString] rangeOfString:_tag].location != NSNotFound && [fileList indexOfObject:fullPath] == NSNotFound)
{
[fileList addObject:f];
[atarget performSelector:aselector withObject:f];
}
if (_cancelSearch)
return fileList;
}
}
else
{
NSString* fileN = [fullPath lastPathComponent];
if ([[fileN lowercaseString] rangeOfString:_tag].location != NSNotFound && [fileList indexOfObject:fullPath] == NSNotFound)
{
[fileList addObject:fullPath];
[atarget performSelector:aselector withObject:fullPath];
}
if (_cancelSearch)
return fileList;
}
}
}
return fileList;
}
вызова функции библиотеки из пользовательского интерфейса
-(void)cancelClick:(id)sender
{
macSearch.cancelSearch = YES; ///setting the cancel to yes so that the library function may come to know that the search is canceled and now stop searching return what ever is searched
}
-(void)wholeSystemScan:(id)sender
{
if([[searchKeyword stringValue] length] < 1)
{
[[[MessageBoxHelper alloc] init] ShowMessageBox:@"Please enter a keyword to search." Title:@"Information" IsAlert:YES];
return;
}
[self ScanStartDisableControls];
NSString* keyw = [searchKeyword stringValue];
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.techheal.fileSearch", 0);
dispatch_async(backgroundQueue, ^{
[macSearch searchWholeSystem:keyw selector:@selector(refreshSelector:) target:self];
[self ScanCompletedEnableControls];
});
}
по мне вы сделали комплексную реализацию немного. Если вы в порядке, я могу предложить вам переработанную структуру, в которой вы можете пойти дальше. Просто дайте мне знать –
Несомненно, большое спасибо @ aman.sood 'killerof99kings' - мой идентификатор skype в случае необходимости –