问题
One of the nice features of BBEdit is how it keeps track of files no matter what happens to those files. The application that I am working on needs to keep track of the location of a number of files owned by the user. The user can move or delete these files and my application needs to know where those files are even if my application was not running at the time the change in location happened.
What is a recommended strategy for this problem or what could it be?
Keeping track of files while the application is running is not the problem. I want the correct path to the files when my application is running no matter what happened to those files when my application was not running.
Is manually searching for the files the best approach or is there an API that I am overlooking that makes this easier?
回答1:
Starting from 10.6, it is done by “Bookmarks” functionality of NSURL
:
Bookmarks are a new facility for generating persistent references to resources identified by URLs. A bookmark is a data object generated by the system from a resource URL. The bookmark data encapsulates a durable, opaque reference to the underlying resource as well as value of resource properties captured when the bookmark was created. A bookmark can be stored in memory or on disk and later used to access the resource property values it contains, or resolved to cover the underlying resource’s URL. In the case of file system resources, the bookmark is capable of locating resources that have been moved or renamed since the bookmark was created, similar to Alias Manager aliases. Note that in this release, bookmarks resolve only by path.
The following new NSURL methods are further documented in NSURL.h:
- (NSData *)bookmarkDataWithOptions:(NSURLBookmarkCreationOptions)options includingResourceValuesForKeys:(NSArray *)keys relativeToURL:( NSURL*)relativeURL error:(NSURL **)error; - (NSURL*)initByResolvingBookmarkData:(NSData*)bookmarkData options:(NSURLBookmarkResolutionOptions)options relativeToURL:(NSURL *)relativeURL bookmarkDataIsStale:(BOOL *)isStale error:(NSError **)error; + (NSURL *)URLByResolvingBookmarkData:(NSData *)bookmarkData options:(NSURLBookmarkResolutionOptions)options relativeToURL:(NSURL *)relativeURL bookmarkDataIsStale:(BOOL *)isStale error:(NSError **)error; + (NSDictionary *)resourceValuesForKeys:(NSArray *)keys fromBookmarkData:(NSData *)bookmarkData;
Before 10.6, it was done with aliases.
来源:https://stackoverflow.com/questions/10276026/how-do-i-keep-track-of-file-locations-on-mac-os-x