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

我的未来我决定 提交于 2019-12-11 08:26:52

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/9746989/icloud-getting-an-array-of-txt-files-present-in-the-cloud-on-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!