为什么这段代码导致NSMetadataQuery崩溃?

时间:2012-01-21 07:49:50

标签: cocoa crash exc-bad-access key-value-observing nsmetadataquery

我有一个非常简单的Xcode项目。它有一个文件应用程序委托,包含以下内容

@interface TestController : NSObject <NSApplicationDelegate, NSMetadataQueryDelegate>

@property (assign) IBOutlet NSWindow *window;
@property (strong, nonatomic) NSString *text;
@property (strong, nonatomic) NSMetadataQuery *query;

@end


@implementation TestController

@synthesize window = _window;
@synthesize text = _text;
@synthesize query = _query;

- (id)init {
    self = [super init];
    if (self) {
        self.query = [[NSMetadataQuery alloc] init];
        self.query.searchScopes = [NSArray arrayWithObject:NSMetadataQueryLocalComputerScope];
        self.query.predicate = [NSPredicate predicateWithFormat:@"kMDItemTextContent LIKE[cd] %@", @"test"];
        self.query.delegate = self;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(queryNote:)
                                                     name:nil
                                                   object:self.query];

        [self.query startQuery];
        [self addObserver:self forKeyPath:@"text" options:0 context:NULL];
    }
    return self;
}

- (void)queryNote:(NSNotification *)note {
    NSLog(@"queryNote: %@", [note name]);
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"text"]) {
        NSString *str = self.text ? self.text : @"test";
        self.query.predicate = [NSPredicate predicateWithFormat:@"kMDItemTextContent LIKE[cd] %@", str];
    }
}

@end

在界面构建器中,我有一个单个数组控制器,其内容数组绑定到测试控制器的query.results密钥路径。我还有一个NSSearchField,其值绑定到text字符串。当我在搜索字段中输入单个字符时,整个程序在EXC_BAD_ACCESS上崩溃。我把它缩小了,并想出如果我在self.query.predicate函数中设置-setText,那么一切似乎都能正常工作。此外,将self.query.predicate设置包装在GCD块中也可以。问题是,为什么在KVO通知中更改NSMetadataQuery的谓词会导致程序崩溃? (我检查了从主线程btw调用的所有内容)

我在github上安装了测试项目,因此您可以轻松克隆并检查问题。

https://github.com/tonyxiao/NSMetadataQueryCrash

0 个答案:

没有答案