Search code examples
macoscocoaicloudnsmetadataquery

iCloud: Getting an array of txt files present in the cloud on OS X


I am trying to get an array of txt files in my app's iCloud folder using a NSMetadataQuery as recommended by Apple:

NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]]; 

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K ENDSWITH '.txt'", NSMetadataItemFSNameKey];
[query setPredicate:pred];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];

[query startQuery];

Unfortunately queryDidFinishGathering: never gets called. What am I doing wrong?

Thanks!


Solution

  • You're using ARC, which means that you need to retain a strong reference to objects that you allocate or they will go away.

    You are calling alloc on your query object, which under manual retain/release would mean that the query object would remain alive until you send it a release or autorelease message.

    However, under ARC, the compiler inserts those calls for you and because it doesn't know that you want the query object to stick around, it releases the query object after you call [query startQuery]. Because the object has been released, it never posts the notification.

    You should instead hold a strong reference to the query object. The most straightforward way to do this is to make it an instance variable, or a strong property.

    @interface YourObject : NSObject
    {
        NSMetadataQuery *query;
    }
    @end
    

    or

    @interface YourObject : NSObject{}
    @property (strong) NSMetadataQuery *query;
    @end