Search code examples
iosswiftnsmetadataquery

metadataquery deallocation before stopquery


I'm using NSMetadataQuery to obtain a list of files in the iCloud ubiquity Documents directory in order to populate a tableview. The code seems to be working, but I get an error stating that the query is being deallocated without first calling stopQuery. I can't seem to find a discussion on this topic. Am I missing something simple here?

Here is the function for the query and for the notification:

var myMetadataQuery : NSMetadataQuery = NSMetadataQuery()
var cloudBackFiles : [AnyObject] = [AnyObject]()

func metadataForListOfFiles() {

    myMetadataQuery.predicate = NSPredicate(format: "%K like '*.sqlite'", NSMetadataItemFSNameKey)//change to "%K like '*.sqlite'"
    myMetadataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "metadataQueryDidFinishGathering:", name: NSMetadataQueryDidFinishGatheringNotification, object: myMetadataQuery)

    myMetadataQuery.startQuery()

}//metadataForListOfFiles

func metadataQueryDidFinishGathering(notification : NSNotification) -> [AnyObject] {

    let query : NSMetadataQuery = notification.object as! NSMetadataQuery
    query.disableUpdates()

    NSNotificationCenter.defaultCenter().removeObserver(self, name: NSMetadataQueryDidFinishGatheringNotification, object: query)

    query.stopQuery()

    let results = query.results

    cloudBackFiles = []

    if (query.resultCount >= 1) {
        println("query.resultCount = \(query.resultCount)")

        for var i = 0; i < query.resultCount; i++ {
            var forResultString = results[i].valueForAttribute(NSMetadataItemFSNameKey) as! String
            println("results[\(i)].value = \(forResultString)")
            var forResultStringNoExt = forResultString.stringByDeletingPathExtension
            cloudBackFiles.append(forResultStringNoExt)
        }//for

    } else {

        println("The query.resultCount was 0!")

    }//if count else
    println("cloudBackFiles list is: ")
    println(cloudBackFiles)

    //justForTest = results

    return results

}//metadataQueryDidFinishGathering(x)

And this is the error:

2015-04-24 22:49:38.367 [26397:2377464] is being deallocated without first calling -stopQuery. To avoid race conditions, you should first invoke -stopQuery on the run loop on which -startQuery was called

Any guidance would be appreciated.


Solution

  • I believe I was recursively calling the metadata query. I rewrote the viewDidLoad and viewWillAppear methods of the tableview controller and I now believe the code above is working properly.