我正在跟踪带有书签的文件的位置,该书签存储在NSUserDefaults中,因此如果用户决定移动它,我的应用程序仍然可以访问它。我用
创建了初始书签- (NSData *)bookmarkFromURL:(NSURL *)url {
NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationMinimalBookmark
includingResourceValuesForKeys:NULL
relativeToURL:NULL
error:NULL];
return bookmark;
}
每次我需要文件时,我从NSUserDefaults检索书签,然后用
解析NSURL- (NSURL *)urlFromBookmark:(NSData *)bookmark {
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark
options:NSURLBookmarkResolutionWithoutUI
relativeToURL:NULL
bookmarkDataIsStale:NULL
error:NULL];
return url;
}
它就像一个魅力。我想要的唯一附加功能是能够检测用户是否删除了该文件。当然,我可以定期检查NSURL是否返回nil,但我希望立即得到通知。我怎么能这样做?
答案 0 :(得分:1)
您将需要使用NSNotification来检测书签何时被删除,然后我想保存到NSUserDefaults。
类中可以删除书签的内容;
-(void)deleteBookmark:(NSData*)bkmark{
[[NSNotificationCenter defaultCenter]postNotificationName:@"XXBookmarkDeletedNotification" object:nil];
}
然后设置另一个类来监听通知并回复它。
// Setup the notification when the object is initialised or view is loaded.
-(void)setupNotifications{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleBookmarkDeletedNotification:) name:@"XXBookmarkDeletedNotification" object:nil];
}
-(void)handleBookmarkDeletedNotification:(NSNotification*)notification{
// do whatever you need to do here, for example set a "deleted" flag in NSUserDefaults
}
// You to need to remove your class from the list of observers when you are done.
-(void)removeNotifications{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"XXBookmarkDeletedNotification" object:nil];
}