首页 > 解决方案 > 如何在 dispatch_async 内将 NSInteger __block 变量设置为 comboboxFilter.indexOfSelectedItem

问题描述

我一直在尝试将 NSInteger 块变量设置为线程内组合框的选定索引的值。该变量在 dispatch_async 之外始终为零,即使它已在 dispatch_async 内部设置。

当我从 dispatch_async 中 NSLog 变量“comboboxFilterSelectedIndex”的值时,它保存正确的索引值,但是在返回 DoSearch 线程时它会丢失该值。

不用说,我不精通目标 c,肯定会需要一些帮助。

谢谢

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    doSearch(directoryURL, words, self->tableContents, self.tableViewOutlet, self.checkboxLookInPathOutlet, self.checkboxContainsAllWordsOutlet, self.checkboxContainsWholeWordsOutlet, self.comboboxFilterOutlet, self.labelHitCountOutlet, self.imageViewThumbnailOutlet, self.labelFilesCountOutlet, self.textViewMetadataOutlet, self.labelElapsedTimeOutlet);
    //dispatch_async(dispatch_get_main_queue(), ^(){


    // Next 2 must be used in main thread only
    dispatch_async(dispatch_get_main_queue(), ^{
        self.buttonSearchOutlet.enabled = true;
        self.buttonSearchOutlet.title = @"Search";
    });
    return;

    //});
});


void doSearch(NSURL *searchPathURL, NSArray *searchWords, 
    NSMutableArray *tableContents, NSTableView *tableView, NSButton 
    *checkboxLookInPath, NSButton *checkboxContainsAllWords, NSButton 
   *checkboxContainsWholeWords, NSComboBox *comboboxFilter, 
    NSTextField *labelHitCount, NSImageView * imageViewThumbnail, 
    NSTextField *labelFilesCount, NSTextView *textViewMetadata, 
    NSTextField *labelElapsedTime){

    For ...{

        //__block NSInteger comboboxFilterSelectedIndex = All;
        __block NSInteger comboboxFilterSelectedIndex = 0;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"------------>%lu", comboboxFilter.indexOfSelectedItem); // Value is correct
            comboboxFilterSelectedIndex = comboboxFilter.indexOfSelectedItem;
            NSLog(@"------------>%lu", comboboxFilterSelectedIndex); // Value is correct
        });

        NSLog(@"------------>%lu", comboboxFilterSelectedIndex); //Value is Always = 0

        ...
    }
}

标签: objective-ccodeblocksosx-mavericksdispatch-async

解决方案


推荐阅读