OSX Yosemite在NSURL上引入了一個非常方便的屬性:NSURLDocumentIdentifierKey
。爲什麼NSURL的NSURLDocumentIdentifierKey(幾乎)總是零?
從文檔報價:
NSURLDocumentIdentifierKey
The document identifier returned as an NSNumber (read-only). The document identifier is a value assigned by the kernel to a file or directory. This value is used to identify the document regardless of where it is moved on a volume. The identifier persists across system restarts. It is not transferred when the file is copied, but it survives "safe save」 operations. For example, it remains on the path to which it was assigned, even after calling the replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: method. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
Available in OS X v10.10 and iOS 8.0.
不幸的是,價值似乎主要零(除了看起來完全斷開一個到另一個罕見的例子)。
特別是,該代碼會拋出異常,在最後一行(在優勝美地10.10.3測試):
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *attributesFlags = @[NSURLNameKey, mNSURLDocumentIdentifierKey];
NSDirectoryEnumerator *en = [fileManager enumeratorAtURL:[NSURL URLWithString:NSHomeDirectory()]
includingPropertiesForKeys:attributesFlags
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error) {
NSAssert(NO, @"An error has occured");
return YES;
}];
for(NSURL *URL in en) {
NSNumber *documentID = nil;
NSError *error = nil;
BOOL result = [URL getResourceValue:&documentID forKey:NSURLDocumentIdentifierKey error:&error]; \
NSAssert(result == YES && error==nil, @"Unable to read property. Error: %@", error); \
NSLog(@"Processing file: %@", URL);
// This will break most of the times
NSAssert(documentID != nil, @"Document ID should not be nil!!");
}
也許我誤解的文件,但在我看來NSURLDocumentIdentifierKey
應該可以上的每個文件在磁盤上。
這裏所涉及的沙盒? – stevesliva
我不這麼認爲:我根本不使用沙盒。除非這是一個MAS專用功能,但我不這麼認爲。 – duhanebel